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)
Visual Basic (Declaración)
Public Class Timer
Inherits Component
public class Timer : Component
public ref class Timer : public Component
public class Timer extends Component
public class Timer extends Component
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.
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. |
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.
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
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 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
{
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
System.Object
System.MarshalByRefObject
System.ComponentModel.Component
System.Windows.Forms.Timer
Seguridad para subprocesos
Los miembros estáticos públicos (Shared en Visual Basic) 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.
Windows 98, Windows 2000 Service Pack 4, Windows CE, Windows Millennium, Windows Mobile para Pocket PC, Windows Mobile para Smartphone, Windows Server 2003, Windows XP Media Center, Windows XP Professional x64, Windows XP SP2, Windows XP Starter
Microsoft .NET Framework 3.0 es compatible con Windows Vista, Microsoft Windows XP SP2 y Windows Server 2003 SP1.
.NET Framework
Compatible con: 3.0, 2.0, 1.1, 1.0
.NET Compact Framework
Compatible con: 2.0, 1.0