如何为WebBrowser导航事件设置超时时间

9

我该如何为WebBrowser的Navigate (URL)事件设置超时时间?

C# .Net Framework 4.0

2个回答

12

当然可以使用计时器。例如:

    public void NavigateTo(Uri url) {
        webBrowser1.Navigate(url);
        timer1.Enabled = true;
    }

    private void timer1_Tick(object sender, EventArgs e) {
        timer1.Enabled = false;
        MessageBox.Show("Timeout on navigation");
    }

    private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e) {
        if (e.Url == webBrowser1.Url && timer1.Enabled) {
            timer1.Enabled = false;
            // etc..
        }
    }

2
不,没有结束的东西。只需导航到其他地方即可。 - Hans Passant
1
当计时器触发时,我会导航到其他地方吗? - Furkan Gözükara
我会像这样注册这个事件,对吧? webBrowser1.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(webBrowser1_DocumentCompleted); - Furkan Gözükara
1
我想结束之前的导航事件。我如何在不导航到其他地方的情况下做到这一点? - Furkan Gözükara
2
webBrowser1.DocumentText = "Canceled"; 就可以了。 - Hans Passant
显示剩余2条评论

0

我正在使用基于NavigatingNavigated事件的以下方法。观察这两个事件之间的时间以重定向到主页。

        //Navigation Timer
        timer2.Enabled = true;
        timer2.Interval = 30000;

        br.DocumentCompleted += browser_DocumentCompleted;
        br.DocumentCompleted += writeToTextBoxEvent;
        br.Navigating += OnNavigating;
        br.Navigated  += OnNavigated;

        br.ScriptErrorsSuppressed = true;
        br.Navigate(ConfigValues.websiteUrl);

    private void OnNavigating(object sender, WebBrowserNavigatingEventArgs e)
    {
        //Reset Timer
        timer2.Stop();
        timer2.Start();

        WriteLogFunction("OnNavigating||||||"+e.Url.ToString());
    }

    private void OnNavigated(object sender, WebBrowserNavigatedEventArgs e)
    {
        //Stop Timer
        timer2.Stop();

        WriteLogFunction("NAVIGATED <><><><><><><> " + e.Url.ToString());
    }


    private void timer2_Tick(object sender, EventArgs e)
    {
        WriteLogFunction(" Navigation Timeout TICK");
        br.Stop();
        br.Navigate(ConfigValues.websiteUrl);
    }

参考资料

  1. 创建网页浏览器加载方法的超时
  2. 如果页面无法加载,则设置网页浏览器超时

那么 br.Stop() 会导致 Web 浏览器控件停止尝试导航吗? - crush

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接