C# 向 Windows 窗体应用程序添加计时器

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1142828/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 09:15:14  来源:igfitidea点击:

Add timer to a Windows Forms application

c#winforms

提问by knowledgehunter

I want to add a timer rather than a countdown which automatically starts when the form loads. Starting time should be 45 minutes and once it ends, i.e. on reaching 0 minutes, the form should terminate with a message displayed. How can I do this?

我想添加一个计时器,而不是在表单加载时自动启动的倒计时。开始时间应为 45 分钟,一旦结束,即在达到 0 分钟时,该表单应以显示消息结束。我怎样才能做到这一点?

Language: preferably C#.

语言:最好是C#。

采纳答案by Tim

Bit more detail:

更多细节:

    private void Form1_Load(object sender, EventArgs e)
    {
        Timer MyTimer = new Timer();
        MyTimer.Interval = (45 * 60 * 1000); // 45 mins
        MyTimer.Tick += new EventHandler(MyTimer_Tick);
        MyTimer.Start();
    }

    private void MyTimer_Tick(object sender, EventArgs e)
    {
        MessageBox.Show("The form will now be closed.", "Time Elapsed");
        this.Close();
    }

回答by Maestro1024

Something like this in your form main. Double click the form in the visual editor to create the form load event.

像这样的东西在你的表单中。在可视化编辑器中双击表单以创建表单加载事件。

 Timer Clock=new Timer();
 Clock.Interval=2700000; // not sure if this length of time will work 
 Clock.Start();
 Clock.Tick+=new EventHandler(Timer_Tick);

Then add an event handler to do something when the timer fires.

然后添加一个事件处理程序以在计时器触发时执行某些操作。

  public void Timer_Tick(object sender,EventArgs eArgs)
  {
    if(sender==Clock)
    {
      // do something here      
    }
  }

回答by Sunil Jere

Download http://download.cnet.com/Free-Desktop-Timer/3000-2350_4-75415517.html

下载http://download.cnet.com/Free-Desktop-Timer/3000-2350_4-75415517.html

Then add a button or something on the form and inside its event, just open this app ie:

然后在表单上和它的事件中添加一个按钮或其他东西,只需打开这个应用程序,即:

{

{

Process.Start(@"C:\Program Files (x86)\Free Desktop Timer\DesktopTimer");

Process.Start(@"C:\Program Files (x86)\Free Desktop Timer\DesktopTimer");

}

}