计时器每秒触发一次并更新 GUI(C# Windows 窗体) [英] Timer firing every second and updating GUI (C# Windows Forms)
问题描述
我有一个 Windows 窗体应用程序,我需要一个计时器工作 90 秒,并且应该在它过去后显示每一秒,有点像秒表 1..2..3 等,在 90 秒后,它应该抛出一个异常,指出有问题.
I have a Windows Forms application where I need to have a timer working for 90 seconds and every second should be shown after it elapses, kind of like a stopwatch 1..2..3 etc, after 90 seconds is up, it should throw an exception that something is wrong.
我有以下代码,但 RunEvent
永远不会触发.
I have the following code, but the RunEvent
never fires.
private void ScanpXRF()
{
bool demo = false;
System.Windows.Forms.Timer timer = new System.Windows.Forms.Timer();
try
{
for (int timerCounter = 0; timerCounter < 90; timerCounter++)
{
timer.Interval = 1000;
timer.Tick += new EventHandler(RunEvent);
timer.Start();
if(timerCounter == 89) {
throw new Exception();
}
}
}
catch (Exception e)
{
timer.Dispose();
MessageBox.Show("There is a problem!");
}
}
private void RunEvent(object sender, System.EventArgs e)
{
//boxStatus.AppendText("RunEvent() called at " + DateTime.Now.ToLongTimeString() + "\n");
MessageBox.Show("timer fired!");
}
我在这里做错了什么,或者还有其他方法可以实现相同的结果吗?
Is there anything I am doing wrong here or are there other suggestions for other ways to achieve the same result?
推荐答案
需要在表单层面声明一个定时器,否则表单关闭时可能不会被销毁:
A timer needs to be declared at the form level, or else it may not be disposed of when the form closes:
System.Windows.Forms.Timer timer;
int counter = 0;
您的启动代码应该只是启动计时器:
Your starting code should just start the timer:
private void ScanpXRF()
{
counter = 0;
timer = new System.Windows.Forms.Timer();
timer.Interval = 1000;
timer.Tick += RunEvent;
timer.Start();
}
RunEvent 是每秒被调用的 Tick 事件,因此您的逻辑需要进入:
The RunEvent is your Tick event being called every second, so your logic needs to go in there:
private void RunEvent(object sender, EventArgs e)
{
counter++;
if (counter >= 90) {
timer.Stop();
// do something...
}
}
这篇关于计时器每秒触发一次并更新 GUI(C# Windows 窗体)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!