使用英语阅读

通过


Timer.Tick 事件

定义

当指定的计时器间隔已过去而且计时器处于启用状态时发生。

public event EventHandler Tick;

事件类型

示例

下面的代码示例实现一个简单的间隔计时器,该计时器每隔五秒发出一次警报。 发生警报时, MessageBox 将显示警报已启动的次数的计数,并提示用户是否应继续运行计时器。

public class Class1 {
    static System.Windows.Forms.Timer myTimer = new System.Windows.Forms.Timer();
    static int alarmCounter = 1;
    static bool exitFlag = false;
 
    // This is the method to run when the timer is raised.
    private static void TimerEventProcessor(Object myObject,
                                            EventArgs myEventArgs) {
       myTimer.Stop();
 
       // Displays a message box asking whether to continue running the timer.
       if(MessageBox.Show("Continue running?", "Count is: " + alarmCounter, 
          MessageBoxButtons.YesNo) == DialogResult.Yes) {
          // Restarts the timer and increments the counter.
          alarmCounter +=1;
          myTimer.Enabled = true;
       }
       else {
          // Stops the timer.
          exitFlag = true;
       }
    }
 
    public static int Main() {
       /* Adds the event and the event handler for the method that will 
          process the timer event to the timer. */
       myTimer.Tick += new EventHandler(TimerEventProcessor);
 
       // Sets the timer interval to 5 seconds.
       myTimer.Interval = 5000;
       myTimer.Start();
 
       // Runs the timer, and raises the event.
       while(!exitFlag) {
          // Processes all the events in the queue.
          Application.DoEvents();
       }
    return 0;
    }
 }

注解

Assert从 事件内部TickDebug 类调用 方法可能无法按预期方式运行,因为显示断言对话框可能会导致 Windows 重复引发Tick事件。 建议不要在此事件中测试断言,而是改用 WriteWriteIfWriteLineWriteLineIf 方法。

有关处理事件的详细信息,请参阅 处理和引发事件

适用于

产品 版本
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
Windows Desktop 3.0, 3.1, 5, 6, 7, 8, 9, 10