打开程序后X秒启动的C#中的计时器?

时间:2012-05-19 13:17:50

标签: c# winforms

如何在程序打开后10秒钟后运行一个功能。

这就是我尝试过的,而且我无法让它发挥作用。

private void button1_Click(object sender, EventArgs e)
{
    Timer tm = new Timer();
    tm.Enabled = true;
    tm.Interval = 60000;
    tm.Tick+=new EventHandler(tm_Tick);
}
private void tm_Tick(object sender, EventArgs e)
{
    Form2 frm = new Form2();
    frm.Show();
    this.Hide();
}

2 个答案:

答案 0 :(得分:14)

你有一些问题:

  1. 您需要使用Load事件而非按钮点击处理程序。
  2. 您应将间隔设置为10000,等待10秒钟。
  3. 您正在为计时器实例使用局部变量。这使您很难在以后引用计时器。使计时器实例成为表单类的成员。
  4. 请记住在运行表单后停止时钟,或者,它会尝试每10秒钟打开一次
  5. 换句话说,就像这样:

    private Timer tm;
    
    private void Form1_Load(object sender, EventArgs e)
    {
        tm = new Timer();
        tm.Interval = 10 * 1000; // 10 seconds
        tm.Tick += new EventHandler(tm_Tick);
        tm.Start();
    }
    
    private void tm_Tick(object sender, EventArgs e)
    {
        tm.Stop(); // so that we only fire the timer message once
    
        Form2 frm = new Form2();
        frm.Show();
        this.Hide();
    }
    

答案 1 :(得分:0)

对你的程序会有什么好处吗?

namespace Timer10Sec
{
    class Program
    {
        static void Main(string[] args)
        {
            Thread t = new Thread(new ThreadStart(After10Sec));
            t.Start();
        }

        public static void After10Sec()
        {
            Thread.Sleep(10000);
            while (true)
            {
                Console.WriteLine("qwerty");
            }
        }
    }
}