捕获和处理Web浏览器关闭事件

时间:2013-02-07 02:23:31

标签: c# events webbrowser-control

我正在使用Windows窗体和WebBrowser控件,我需要捕获和处理WebBrowser Controls调用以关闭。

我已经看过这个,但它不能正常工作,因为我需要它:http://blogs.artinsoft.net/Mrojas/archive/2009/05/21/Extended-WebBrowser-Control-Series-WebBrowser-Control-and-windowClose().aspx

这是我得到的消息:

---------------------------
Web Browser
---------------------------
The webpage you are viewing is trying to close the window.

Do you want to close this window?
---------------------------
Yes   No   
---------------------------

我需要捕获此事件并禁止它,然后执行一个函数。有谁知道一个简单的方法来做到这一点?

2 个答案:

答案 0 :(得分:9)

在到处搜索并没有真正得到我需要的东西之后,我偶然发现了一个偶然的参考:

HtmlDocument htmlDocument = this.webBrowser1.Document;
htmlDocument.Window.Unload += new HtmlElementEventHandler(Window_Unload);

在关闭和处理WebBrowser控件之前,Document确实已卸载。

void Window_Unload(object sender, HtmlElementEventArgs e)
{
    // Do your stuff here...
    // Call Method...
    // Close Form...
}

现在这对我有用了。

答案 1 :(得分:0)

可能你是用Javascript关闭这个窗口的。基本上这是安全原因。除非脚本本身打开,否则无法关闭窗口。可能的解决方案可能是使用此Javascript代码

function CloseWindow()
{
   window.open('','_self','');
   window.close();
}

以下是相同示例的链接

https://msmvps.com/blogs/paulomorgado/archive/2007/11/02/how-to-close-browser-windows-in-windows-internet-explorer-7.aspx

但我不确定IE的所有版本。

相关问题