Timer Timer Timer Timer Class

定义

实现按用户定义的时间间隔引发事件的计时器。Implements a timer that raises an event at user-defined intervals. 此计时器最宜用于 Windows 窗体应用程序中,并且必须在窗口中使用。This timer is optimized for use in Windows Forms applications and must be used in a window.

public ref class Timer : System::ComponentModel::Component
public class Timer : System.ComponentModel.Component
type Timer = class
    inherit Component
Public Class Timer
Inherits Component
继承

示例

下面的示例实现了一个简单的间隔计时器, 每隔五秒就会发出警报。The following example implements a simple interval timer, which sets off an alarm every five seconds. 当出现警报时, MessageBox会显示警报启动的次数, 并提示用户确定计时器是否应继续运行。When the alarm occurs, a MessageBox displays a count of the number of times the alarm has started and prompts the user as to whether the timer should continue to run.

public ref class Class1
{
private:
   static System::Windows::Forms::Timer^ myTimer = gcnew System::Windows::Forms::Timer;
   static int alarmCounter = 1;
   static bool exitFlag = false;

   // This is the method to run when the timer is raised.
   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?", String::Format( "Count is: {0}", 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 void Main()
   {
      
      /* Adds the event and the event handler for the method that will 
                process the timer event to the timer. */
      myTimer->Tick += gcnew EventHandler( TimerEventProcessor );
      
      // Sets the timer interval to 5 seconds.
      myTimer->Interval = 5000;
      myTimer->Start();
      
      // Runs the timer, and raises the event.
      while ( exitFlag == false )
      {
         
         // Processes all the events in the queue.
         Application::DoEvents();
      }
   }

};

int main()
{
   Class1::Main();
}

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 == false) {
          // Processes all the events in the queue.
          Application.DoEvents();
       }
    return 0;
    }
 }
    
Public Class Class1
    Private Shared WithEvents myTimer As New System.Windows.Forms.Timer()
    Private Shared alarmCounter As Integer = 1
    Private Shared exitFlag As Boolean = False    
    
    ' This is the method to run when the timer is raised.
    Private Shared Sub TimerEventProcessor(myObject As Object, _
                                           ByVal myEventArgs As EventArgs) _
                                       Handles myTimer.Tick
        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 Then
            ' Restarts the timer and increments the counter.
            alarmCounter += 1
            myTimer.Enabled = True
        Else
            ' Stops the timer.
            exitFlag = True
        End If
    End Sub
    
    Public Shared Sub Main()
        ' Adds the event and the event handler for the method that will
        ' process the timer event to the timer.
        
        ' Sets the timer interval to 5 seconds.
        myTimer.Interval = 5000
        myTimer.Start()
        
        ' Runs the timer, and raises the event.
        While exitFlag = False
            ' Processes all the events in the queue.
            Application.DoEvents()
        End While

    End Sub    

End Class

注解

Timer用于按用户定义的时间间隔引发事件。A Timer is used to raise an event at user-defined intervals. 此 Windows 计时器适用于单线程环境, 在此环境中, UI 线程用于执行处理。This Windows timer is designed for a single-threaded environment where UI threads are used to perform processing. 它要求用户代码提供 UI 消息泵, 并且始终从同一线程操作, 或将调用封送到其他线程。It requires that the user code have a UI message pump available and always operate from the same thread, or marshal the call onto another thread.

使用此计时器时, 使用Tick事件执行轮询操作, 或在指定的时间段内显示初始屏幕。When you use this timer, use the Tick event to perform a polling operation or to display a splash screen for a specified period of time. true Interval Interval每当属性设置为且属性大于零时, 将根据属性设置的Tick时间间隔引发事件。 EnabledWhenever the Enabled property is set to true and the Interval property is greater than zero, the Tick event is raised at intervals based on the Interval property setting.

此类提供一些方法来设置间隔, 以及启动和停止计时器。This class provides methods to set the interval, and to start and stop the timer.

备注

Windows 窗体计时器组件是单线程的, 且限制为55毫秒的准确度。The Windows Forms Timer component is single-threaded, and is limited to an accuracy of 55 milliseconds. 如果需要具有更高准确性的多线程计时器, 请Timer使用System.Timers命名空间中的类。If you require a multithreaded timer with greater accuracy, use the Timer class in the System.Timers namespace.

构造函数

Timer() Timer() Timer() Timer()

初始化 Timer 类的新实例。Initializes a new instance of the Timer class.

Timer(IContainer) Timer(IContainer) Timer(IContainer) Timer(IContainer)

将指定的容器与 Timer 类的新实例一起初始化。Initializes a new instance of the Timer class together with the specified container.

属性

CanRaiseEvents CanRaiseEvents CanRaiseEvents CanRaiseEvents

获取一个指示组件是否可以引发事件的值。Gets a value indicating whether the component can raise an event.

(Inherited from Component)
Container Container Container Container

获取 IContainer,它包含 ComponentGets the IContainer that contains the Component.

(Inherited from Component)
DesignMode DesignMode DesignMode DesignMode

获取一个值,用以指示 Component 当前是否处于设计模式。Gets a value that indicates whether the Component is currently in design mode.

(Inherited from Component)
Enabled Enabled Enabled Enabled

获取或设置计时器是否正在运行。Gets or sets whether the timer is running.

Events Events Events Events

获取附加到此 Component 的事件处理程序的列表。Gets the list of event handlers that are attached to this Component.

(Inherited from Component)
Interval Interval Interval Interval

获取或设置在相对于上一次发生的 Tick 事件引发 Tick 事件之前的时间(以毫秒为单位)。Gets or sets the time, in milliseconds, before the Tick event is raised relative to the last occurrence of the Tick event.

Site Site Site Site

获取或设置 ComponentISiteGets or sets the ISite of the Component.

(Inherited from Component)
Tag Tag Tag Tag

获取或设置一个任意字符串,表示某种类型的用户状态。Gets or sets an arbitrary string representing some type of user state.

方法

CreateObjRef(Type) CreateObjRef(Type) CreateObjRef(Type) CreateObjRef(Type)

创建一个对象,该对象包含生成用于与远程对象进行通信的代理所需的全部相关信息。Creates an object that contains all the relevant information required to generate a proxy used to communicate with a remote object.

(Inherited from MarshalByRefObject)
Dispose() Dispose() Dispose() Dispose()

释放由 Component 使用的所有资源。Releases all resources used by the Component.

(Inherited from Component)
Dispose(Boolean) Dispose(Boolean) Dispose(Boolean) Dispose(Boolean)

释放由计时器使用的资源(内存除外)。Disposes of the resources, other than memory, used by the timer.

Equals(Object) Equals(Object) Equals(Object) Equals(Object)

确定指定的对象是否等于当前对象。Determines whether the specified object is equal to the current object.

(Inherited from Object)
GetHashCode() GetHashCode() GetHashCode() GetHashCode()

作为默认哈希函数。Serves as the default hash function.

(Inherited from Object)
GetLifetimeService() GetLifetimeService() GetLifetimeService() GetLifetimeService()

检索控制此实例的生存期策略的当前生存期服务对象。Retrieves the current lifetime service object that controls the lifetime policy for this instance.

(Inherited from MarshalByRefObject)
GetService(Type) GetService(Type) GetService(Type) GetService(Type)

返回一个对象,该对象表示由 Component 或它的 Container 提供的服务。Returns an object that represents a service provided by the Component or by its Container.

(Inherited from Component)
GetType() GetType() GetType() GetType()

获取当前实例的 TypeGets the Type of the current instance.

(Inherited from Object)
InitializeLifetimeService() InitializeLifetimeService() InitializeLifetimeService() InitializeLifetimeService()

获取生存期服务对象来控制此实例的生存期策略。Obtains a lifetime service object to control the lifetime policy for this instance.

(Inherited from MarshalByRefObject)
MemberwiseClone() MemberwiseClone() MemberwiseClone() MemberwiseClone()

创建当前 Object 的浅表副本。Creates a shallow copy of the current Object.

(Inherited from Object)
MemberwiseClone(Boolean) MemberwiseClone(Boolean) MemberwiseClone(Boolean) MemberwiseClone(Boolean)

创建当前 MarshalByRefObject 对象的浅表副本。Creates a shallow copy of the current MarshalByRefObject object.

(Inherited from MarshalByRefObject)
OnTick(EventArgs) OnTick(EventArgs) OnTick(EventArgs) OnTick(EventArgs)

引发 Tick 事件。Raises the Tick event.

Start() Start() Start() Start()

启动计时器。Starts the timer.

Stop() Stop() Stop() Stop()

停止计时器。Stops the timer.

ToString() ToString() ToString() ToString()

返回表示 Timer 的字符串。Returns a string that represents the Timer.

事件

Disposed Disposed Disposed Disposed

当通过调用 Dispose() 方法释放组件时发生。Occurs when the component is disposed by a call to the Dispose() method.

(Inherited from Component)
Tick Tick Tick Tick

当指定的计时器间隔已过去而且计时器处于启用状态时发生。Occurs when the specified timer interval has elapsed and the timer is enabled.

适用于