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

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

我已经看了这个,但它不能正常工作,因为我需要它: 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 --------------------------- 

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

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

 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... } 

现在这对我有用。

可能你是用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的所有版本。