Wednesday, November 21, 2007

Closing Form with WebBrowser control after window.close with C#

I recently had this problem. I have a Windows Form that hosts a WebBrowser control. The page in the WebBrowser control closes itself using window.close and when it does that the Windows Form freezes up.

Found a solution here posted by Jeff Sanders on his blog (thanks man!)

The sample code is provided in VB.NET Below is the same code rewritten in C#

public class ExtendedWebBrowser : WebBrowser
{
public const int WM_PARENTNOTIFY = 0x0210;
public const int WM_DESTROY = 2;

public delegate void ClosingEventHandler();
public event ClosingEventHandler Closing;

protected override void WndProc(ref Message m)
{
switch (m.Msg)
{
case WM_PARENTNOTIFY:
if (!this.DesignMode)
{
if (m.WParam.ToInt32() == WM_DESTROY)
{
if (this.Closing != null)
{
this.Closing();
}
}
}
base.DefWndProc(ref m);
break;

default:
base.WndProc(ref m);
break;
}
}
}

No comments: