Timer 類別

定義

實作一個在使用者定義的間隔引發事件的計時器。Implements a timer that raises an event at user-defined intervals. 最佳化這個計時器以用於 Windows Form 應用程式,並且必須用於視窗中。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. 每當 Enabled 屬性設定為 trueInterval 屬性大於零時,就會根據 Interval 屬性設定,以間隔引發 Tick 事件。Whenever 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 Forms 計時器元件是單一執行緒,而且受限於55毫秒的精確度。The Windows Forms Timer component is single-threaded, and is limited to an accuracy of 55 milliseconds. 如果您需要更精確的多執行緒計時器,請使用 System.Timers 命名空間中的 Timer 類別。If you require a multithreaded timer with greater accuracy, use the Timer class in the System.Timers namespace.

建構函式

Timer()

初始化 Timer 類別的新執行個體。Initializes a new instance of the Timer class.

Timer(IContainer)

使用指定的容器,初始化 Timer 類別的新執行個體。Initializes a new instance of the Timer class together with the specified container.

屬性

CanRaiseEvents

取得值,指出元件是否能引發事件。Gets a value indicating whether the component can raise an event.

(繼承來源 Component)
Container

取得包含 IContainerComponentGets the IContainer that contains the Component.

(繼承來源 Component)
DesignMode

取得值,指出 Component 目前是否處於設計模式。Gets a value that indicates whether the Component is currently in design mode.

(繼承來源 Component)
Enabled

取得或設定計時器是否正在執行。Gets or sets whether the timer is running.

Events

取得附加在這個 Component 上的事件處理常式清單。Gets the list of event handlers that are attached to this Component.

(繼承來源 Component)
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

取得或設定 ComponentISiteGets or sets the ISite of the Component.

(繼承來源 Component)
Tag

取得或設定表示部分類型使用者狀態的任意字串。Gets or sets an arbitrary string representing some type of user state.

方法

CreateObjRef(Type)

建立包含所有相關資訊的物件,這些資訊是產生用來與遠端物件通訊的所需 Proxy。Creates an object that contains all the relevant information required to generate a proxy used to communicate with a remote object.

(繼承來源 MarshalByRefObject)
Dispose()

釋放 Component 所使用的所有資源。Releases all resources used by the Component.

(繼承來源 Component)
Dispose(Boolean)

處置計時器所使用記憶體之外的資源。Disposes of the resources, other than memory, used by the timer.

Equals(Object)

判斷指定的物件是否等於目前的物件。Determines whether the specified object is equal to the current object.

(繼承來源 Object)
GetHashCode()

做為預設雜湊函式。Serves as the default hash function.

(繼承來源 Object)
GetLifetimeService()

擷取控制這個執行個體存留期 (Lifetime) 原則的目前存留期服務物件。Retrieves the current lifetime service object that controls the lifetime policy for this instance.

(繼承來源 MarshalByRefObject)
GetService(Type)

傳回表示 Component 或其 Container 所提供之服務的物件。Returns an object that represents a service provided by the Component or by its Container.

(繼承來源 Component)
GetType()

取得目前執行個體的 TypeGets the Type of the current instance.

(繼承來源 Object)
InitializeLifetimeService()

取得存留期服務物件,以控制這個執行個體的存留期原則。Obtains a lifetime service object to control the lifetime policy for this instance.

(繼承來源 MarshalByRefObject)
MemberwiseClone()

建立目前 Object 的淺層複製。Creates a shallow copy of the current Object.

(繼承來源 Object)
MemberwiseClone(Boolean)

建立目前 MarshalByRefObject 物件的淺層複本。Creates a shallow copy of the current MarshalByRefObject object.

(繼承來源 MarshalByRefObject)
OnTick(EventArgs)

引發 Tick 事件。Raises the Tick event.

Start()

啟動計時器。Starts the timer.

Stop()

停止計時器。Stops the timer.

ToString()

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

事件

Disposed

當此元件由 Dispose() 方法的呼叫處置時發生。Occurs when the component is disposed by a call to the Dispose() method.

(繼承來源 Component)
Tick

發生於指定的計時器間隔已耗用,且計時器被啟用時。Occurs when the specified timer interval has elapsed and the timer is enabled.

適用於