Timer (Clase) (System.Windows.Forms)

Cambiar vista:
Sin script
Biblioteca de clases de .NET Framework
Timer (Clase)

Actualización: noviembre 2007

Implementa un temporizador que provoca un evento en los intervalos definidos por el usuario. Este temporizador está optimizado para su uso en aplicaciones de Windows Forms y se debe utilizar en una ventana.

Espacio de nombres:  System.Windows.Forms
Ensamblado:  System.Windows.Forms (en System.Windows.Forms.dll)
Sintaxis

Visual Basic (Declaración)
Public Class Timer _
	Inherits Component
Visual Basic (Uso)
Dim instance As Timer
C#
public class Timer : Component
Visual C++
public ref class Timer : public Component
J#
public class Timer extends Component
JScript
public class Timer extends Component
Comentarios

Se utiliza Timer para provocar un evento en los intervalos definidos por el usuario. Este temporizador de Windows está diseñado para entornos de un único subproceso donde los subprocesos de IU se utilizan para realizar el procesamiento. Es necesario que el código del usuario tenga disponible un surtidor de mensajes de IU y que siempre funcione desde el mismo subproceso o que realice el cálculo de referencias a la llamada en otro subproceso.

Al usar este temporizador, utilice el evento Tick para realizar una operación de sondeo o para mostrar una pantalla de inicio durante un período de tiempo determinado. Siempre que la propiedad Enabled se establece en true y la propiedad Interval es mayor que cero, el evento Tick se provoca en los intervalos especificados en la propiedad Interval.

Esta clase proporciona métodos para establecer el intervalo y para iniciar y detener el temporizador.

xdh6857z.alert_note(es-es,VS.90).gif Nota:

El componente Temporizador de los formularios Windows Forms tiene un único subproceso y está limitado a una precisión de 55 milisegundos. Si necesita un temporizador de varios subprocesos con una precisión mayor, utilice la clase Timer del espacio de nombres System.Timers.

Ejemplos

El siguiente ejemplo implementa un temporizador de intervalo simple, que dispara una alarma cada cinco segundos. Cuando se dispara la alarma, MessageBox muestra el número de veces que ésta se ha activado y pregunta al usuario si debe seguir funcionando el temporizador.

Visual Basic
Public Class Class1
    Private Shared 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, _
                                           myEventArgs As EventArgs)
        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.
        AddHandler myTimer.Tick, AddressOf 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()
        End While

    End Sub    

End Class



C#
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;
    }
 }



Visual C++
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();
}



J#
public class Class1
{
    private static System.Windows.Forms.Timer myTimer = 
        new System.Windows.Forms.Timer();
    private static int alarmCounter = 1;
    private static boolean 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).Equals(DialogResult.Yes)) {
            // Restarts the timer and increments the counter.
            alarmCounter += 1;
            myTimer.set_Enabled(true);
        }
        else {
            // Stops the timer.
            exitFlag = true;
        }
    } //TimerEventProcessor

    public static void main(String[] args)
    {
        /* Adds the event and the event handler for the method that will 
           process the timer event to the timer. 
         */
        myTimer.add_Tick(new EventHandler(TimerEventProcessor));

        // Sets the timer interval to 5 seconds.
        myTimer.set_Interval(5000);
        myTimer.Start();

        // Runs the timer, and raises the event.
        while (exitFlag == false) {
            // Processes all the events in the queue.
            Application.DoEvents();
        }
        return;
    } //main
} //Class1


Jerarquía de herencia

System.Object
  System.MarshalByRefObject
    System.ComponentModel.Component
      System.Windows.Forms.Timer
Seguridad para subprocesos

Todos los miembros static (Shared en Visual Basic) públicos de este tipo son seguros para la ejecución de subprocesos. No se garantiza que los miembros de instancias sean seguros para la ejecución de subprocesos.
Plataformas

Windows Vista, Windows XP SP2, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP Starter Edition, Windows Server 2003, Windows Server 2000 SP4, Windows Millennium Edition, Windows 98, Windows CE, Windows Mobile para Smartphone, Windows Mobile para Pocket PC

.NET Framework y .NET Compact Framework no admiten todas las versiones de cada plataforma. Para obtener una lista de las versiones compatibles, vea Requisitos de sistema de .NET Framework.
Información de versión

.NET Framework

Compatible con: 3.5, 3.0, 2.0, 1.1, 1.0

.NET Compact Framework

Compatible con: 3.5, 2.0, 1.0
Vea también

Referencia