运行 倒计时结束后的网页浏览器控件(带计时器)

Run webbrowser control after countdown is finish(with timer)

我想实现一个简单的应用程序,在特定和精确的时间,用浏览器控制,去网页。

    public partial class Form1 : Form
{
    System.DateTime timeStart = new System.DateTime(2016, 05, 25, 19, 30, 00, 00);
    TimeSpan sub;
    bool timeExpires = false;
    public Form1()
    {
        InitializeComponent();
    }

    private void Form1_Load(object sender, EventArgs e)
    {


        timer1.Interval = 100;
        timer1.Start();

        while(timeExpires)
        {
            webBrowser1.Navigate("https://www.google.it/");
        }

    }

    private void timer1_Tick(object sender, EventArgs e)
    {
        System.DateTime Now = System.DateTime.Now;

        sub = timeStart.Subtract(Now);

        if ((int)sub.TotalSeconds == 0)
        {
            this.timer1.Stop();
            MessageBox.Show("ok, Time is up!");
            timeExpires = true;
        }
        else
        {
            textBox1.Text = sub.ToString();
        }


    }
}

计时后,设置timer1.stop()时,显示消息框。

但网络浏览器不会 运行。

我知道我使用布尔变量 timeExpires 是一个 "antiquated" 方法。

我有两个问题:

非常感谢

您的主线程被 while 循环阻塞,因此 messages/events 未被处理。这样,timeExpires 的值在循环内永远不会改变。据您了解,您可以 Application.DoEvents() 强制处理事件,但这可能不是一件好事,除非您真的 understand how this works 以及它有多邪恶。

您应该在 Timer 的 Tick 事件中打开浏览器(就像您调用 MessageBox.Show() 的地方一样)但是要小心不要在 tick 事件上做太多事情,如果您的语句需要更多时间 运行 比定时器的间隔,Tick 事件将再次 运行 并且可能会弄乱一切。所以,要解决这个问题,无论您在 Tick 事件中输入什么,暂停计时器并在完成的地方重新开始。

 private void timer1_Tick(object sender, EventArgs e) {
           timer1.Stop(); // prevent event to fire again, until we get some stuff done
           if(timeStart >= DateTime.Now) {
                openBrowser();
           } else {
              timer1.Start();
              textBox1.Text = sub.ToString();
           }
 }