我需要创建一个基于计时器的应用程序?

时间:2014-03-14 02:29:08

标签: c# timer

我需要创建一个必须有定时器控件的应用程序; 当每个表单被调用时,计时器必须自动初始化,当时间达到3秒意味着它必须加载另一个表单。

我试过这个:

private void Form1_Load(object sender, EventArgs e)
{
    timer1.Start();
    if (timer1.Interval = 3000)
    {
        MessageBox.Show("Times up");
        form2 i=new form2();
        form2.show();
    }
}

但我无法得到正确的结果......

2 个答案:

答案 0 :(得分:1)

C#中的定时器通过定期触发事件来工作。您需要附加一个响应timer事件的事件处理程序。 MSDN documentation有一个简单的例子(下面转载的代码片段)。

public Timer aTimer;

public static void Main()
{
    // Create a timer with a ten second interval.
    aTimer = new System.Timers.Timer(10000);

    // Hook up the Elapsed event for the timer.
    aTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent);

    // Set the Interval to 2 seconds (2000 milliseconds).
    aTimer.Interval = 2000;
    aTimer.Enabled = true;

    Console.WriteLine("Press the Enter key to exit the program.");
    Console.ReadLine();
}

// Specify what you want to happen when the Elapsed event is  
// raised. 
private static void OnTimedEvent(object source, ElapsedEventArgs e)
{
    Console.WriteLine("The Elapsed event was raised at {0}", e.SignalTime);
}

答案 1 :(得分:1)

初始化并启用计时器并将事件处理程序附加到Tick事件。

Timer timer;
private void Form1_Load(object sender, EventArgs e)
{
    timer = new Timer();
    timer.Enabled = true;
    timer.Interval = 3000;
    timer.Tick += timer_Tick;
    timer.Start();
}

private void timer_Tick(object sender, EventArgs e)
{
    MessageBox.Show("Times up");
    Form2 i = new Form2();
    i.Show();
}