Rusty Nail
Rusty Nail

Reputation: 2710

Catching and handling Web Browser Close Event

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?

Upvotes: 4

Views: 11288

Answers (2)

Milan Matějka
Milan Matějka

Reputation: 2752

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.

Upvotes: 0

Rusty Nail
Rusty Nail

Reputation: 2710

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.

Upvotes: 10

Related Questions