C# - Windows Forms - 将应用程序置于后台并恢复它

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

我需要将我的 WindowsForms 应用程序置于后台,然后 "revive" 它。

我希望应用程序非常简单,所以我只是让用户输入一小时和一分钟,而不将其转换为时间戳。

我需要一个函数来测试当前的分钟和小时是否大于用户输入的小时和分钟。

我不想为此浪费资源,所以如果应用程序每分钟测试一次就足够了,即使它不准确。

这是我目前得到的:

// ... 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;

如果我现在 运行 我的代码,我得到以下错误信息(在 运行 出来的时间之后):

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.

如何/应该如何再次显示 window?

不使用 System.Timers.Timer class(在单独的线程上运行),而是使用专门设计用于 WinForms 的 System.Windows.Forms.Timer

这里有更详细的用法信息:https://msdn.microsoft.com/en-us/library/system.windows.forms.timer(v=vs.110).aspx