加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – System.Windows.Forms.Timer继续运行

发布时间:2020-12-15 23:34:57 所属栏目:百科 来源:网络整理
导读:我需要在表单加载10秒后显示一条消息. 我使用以下代码 private void Form1_Load(object sender,EventArgs e){ SetTimeInterval(); }System.Windows.Forms.Timer MyTimer = new System.Windows.Forms.Timer();public void SetTimeInterval(){ MyTimer.Interva
我需要在表单加载10秒后显示一条消息.
我使用以下代码

private void Form1_Load(object sender,EventArgs e)
{
  SetTimeInterval();          
}

System.Windows.Forms.Timer MyTimer = new System.Windows.Forms.Timer();

public void SetTimeInterval()
{           
    MyTimer.Interval = ( 10 * 1000);
    MyTimer.Tick += new EventHandler(TimerEventProcessor);            
    MyTimer.Start();    
}

void TimerEventProcessor(Object myObject,EventArgs myEventArgs)
{
    MessageBox.Show("TIME UP");           

    MyTimer.Stop();
    MyTimer.Enabled = false;
}

使用MyTimer.Stop()和MyTimer.Enabled = false尝试,但messagebox每10秒显示一次.如何在第一次实例后停止它?

解决方法

你的问题是MessageBox.Show()是一个阻塞调用.因此,只有在关闭MessageBox后才会调用MyTimer.Stop().

因此,在关闭MessageBox之前,每10秒会弹出一个新的.简单的解决方案是更改调用顺序:

void TimerEventProcessor(Object myObject,EventArgs myEventArgs)
{
    MyTimer.Stop();
    MyTimer.Enabled = false;
    MessageBox.Show("TIME UP");           
}

因此,在显示消息框之前,只要您进入事件处理程序,计时器就会停止.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读