簡體   English   中英

System.Windows.Forms.Timer繼續運行

[英]System.Windows.Forms.Timer keeps on running

我需要在表單加載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");           
}

因此,在顯示消息框之前,只要您進入事件處理程序,計時器就會停止。

我建議這個方法去theform.designer.cs寫這個代碼

this.timer1.Enabled = true;
this.timer1.Interval = 10000;

並在你的.cs文件中執行此操作

private void timer1_Tick(object sender, EventArgs e)
{
    MessageBox.Show("msg");
}

這對我來說很完美。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM