web浏览器文件已完成事件C# [英] WebBrowser Document Completed Event C#

查看:137
本文介绍了web浏览器文件已完成事件C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面是我为我的浏览器 DocumentCompleted 事件,也是 navBtnClick()方法使用的功能,负责创建Web浏览器和导航到特定的URL。

Below is the function I use as my browsers' DocumentCompleted event, and also the navBtnClick() method which is responsible for creating the web browser and navigating to a specific url.

public void WebBrowser_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e) {

                MessageBox.Show( ((WebBrowser)sender).Url.ToString() );

}



private void navBtnClick(object sender, EventArgs e)
{
            WebBrowser wbrowser = new WebBrowser();
            wbrowser.DocumentCompleted +=new WebBrowserDocumentCompletedEventHandler(WebBrowser_DocumentCompleted);
            wbrowser.Navigate("http://www.google.com");

}

现在经过这行 wbrowser。导航(http://www.google.com); 执行,有正确显示的URL一个消息框,然后过了一会另一个消息框显示了相同的URL。那么,什么情况是,无论是在 DocumentCompleted 事件处理程序,获取执行两次。有人可以帮我一次只执行?

Now after this line wbrowser.Navigate("http://www.google.com"); is executed, there is a message box correctly showing the url, and then after a while another message box shows with the same url. So, what happens is, whatever is on the DocumentCompleted event handler, gets executed twice. Can someone help me make it execute once only?

推荐答案

我记得,DocumentCompleted就会如果文档被导航到触发多次有嵌入其他网页的内部框架。

As I recall, DocumentCompleted will fire multiple times if the document being navigated to has iframes that embed other web pages.

如果您只想接收事件恰好一次,从DocumentCompleted处理器只是退订:

If you only want to receive the event exactly once, just unsubscribe from the DocumentCompleted handler:

public void WebBrowser_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e) 
{
   var webBrowser = sender as WebBrowser;
   webBrowser.DocumentCompleted -= WebBrowser_DocumentCompleted;
   MessageBox.Show(webBrowser.Url.ToString() );
}    

private void navBtnClick(object sender, EventArgs e)
{
     var wbrowser = new WebBrowser();
     wbrowser.DocumentCompleted +=new WebBrowserDocumentCompletedEventHandler(WebBrowser_DocumentCompleted);
     wbrowser.Navigate("http://www.google.com");
}






另外,也可以使用System.IObservable和 ReactiveExtensions 订阅只有一个事件触发:


Alternately, you can use System.IObservable and ReactiveExtensions to subscribe to exactly one event firing:

private void navBtnClick(object sender, EventArgs e)
{
     var browser = new WebBrowser();
     var docCompleted = Observable.FromEventPattern<WebBrowserDocumentCompletedEventArgs>(browser, "DocumentCompleted")
     docCompleted
         .Take(1) // Take only one event firing
         .Subscribe(i => MessageBox.Show(browser.Url.ToString()));

     browser.Navigate("http://www.google.com");
}

这篇关于web浏览器文件已完成事件C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆