Catching and handling Web Browser Close Event

北战南征 提交于 2019-12-06 04:41:57

问题


I am Using Windows Forms and a WebBrowser Control, I am in need of catching and handling the WebBrowser Controls call to close.

I have looked at this but it is not working as I need it to: http://blogs.artinsoft.net/Mrojas/archive/2009/05/21/Extended-WebBrowser-Control-Series-WebBrowser-Control-and-windowClose().aspx

This is the message I get:

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

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

I need to catch this event and suppress it, then perform a function after that. Does anyone know a simple way to do this?


回答1:


After searching everywhere and not really getting what I needed, I managed to stumble onto a by chance reference:

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

The Document does get Unloaded before the WebBrowser Control is closed and disposed.

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

And this is now working for me.




回答2:


Probably you're closing this window by Javascript. Basically this is security reason. You can't close a window unless it is opened by a script itself. Possible solution could be use this Javascript code

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

Here is link to the same example

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

But I am not sure of all versions of IE.



来源:https://stackoverflow.com/questions/14742498/catching-and-handling-web-browser-close-event

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!