Search code examples
c#winformstimerwindow

C# - Windows Forms - Put a app in the background and revive it


I need to put my WindowsForms application in the background and then "revive" it.

I want the application to be very easy, so i just let the user input a hour and a minute without converting it into a timestamp.

I need a function to test if the current minute and hour is bigger than the hour and minute typed by the user.

I don't want to waste Resources for this, so its enough if the application test for this every minute, even if its unexact.

This is what I got so far:

// ... in the same class:
/////////////////////////////////////////////////////////////

private System.Timers.Timer timer = new System.Timers.Timer();

private void TimerRunOut(object source, ElapsedEventArgs e)
{
    DateTime now = DateTime.Now;

    int h_now = Convert.ToInt32(now.ToString("HH"));
    int m_now = Convert.ToInt32(now.ToString("mm"));

    // if the hour is bigger than the current hour
    // if the hour is as big as the current hour and the current minute is bigger than the minute
    if(h_now > hour || h_now == hour && m_now > minute)
    {
        Show();
    }

    // If the hour is as big as the current hour and the minute as big as the current minute
    if (h_now == hour && m_now == minute)
    {
        Show();
    }

}

// ... In a function runned if the timer is set:
/////////////////////////////////////////////////////////////

this.Hide();

timer.Elapsed += new ElapsedEventHandler(TimerRunOut);
timer.Interval = 60000;
timer.Enabled = true;

If I run my code now, I get the following error message (after the time run out):

An exception of type 'System.InvalidOperationException' occurred in System.Windows.Forms.dll but was not handled in user code

Additional information: Cross-thread operation not valid: Control 'Form1' accessed from a thread other than the thread it was created on.

If there is a handler for this exception, the program may be safely continued.

How can / should I show the window again?


Solution

  • Instead of using the System.Timers.Timer class (which runs on a separate thread), use the System.Windows.Forms.Timer which is specifically designed to work with WinForms.

    Here is more detailed information about it's usage: https://msdn.microsoft.com/en-us/library/system.windows.forms.timer(v=vs.110).aspx