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

joh*_*omp 3 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();
}
Run Code Online (Sandbox Code Playgroud)

Dav*_*nan 14

你有一些问题:

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

换句话说,这样的事情:

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();
}
Run Code Online (Sandbox Code Playgroud)