【问题标题】:C# - Windows Forms - Put a app in the background and revive itC# - Windows 窗体 - 将应用程序置于后台并恢复它
【发布时间】:2015-08-29 16:33:54
【问题描述】:

我需要将我的 WindowsForms 应用程序放在后台,然后“恢复”它。

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

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

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

这是我目前得到的:

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

我如何/应该再次显示窗口?

【问题讨论】:

    标签: c# winforms timer window


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多