How To: Close the Form hosting the WebBrowser control when scripting calls window.close in the .Net Framework version 2.0

By design the WebBrowser Control does not close the parent Form when WebBrowser Control is closed.  Here is one way you can accomplish this.

The WebBrowser will send a WM_NOTIFYPARENT notification that can be captured and an event raised that a host can respond to.

Here is the documentation on the WM_NOTIFYPARENT notification:  https://msdn2.microsoft.com/en-us/library/ms632638.aspx

In this case we care about when the WebBrowser is closed, so we will respond to the wParam WM_DESTROY only.  Since I am going to override the WebBrowser control for other purposes, I will simply add an event to this control that any Form can act on.

First define a new VB Windows Project.  Drag and drop the WebBrowser Control onto your form from the Common Controls section of the Toolbox.

Next we want to extend the WebBrowser control so we can process the WndProc function.  Create a new Class(Add, Class) and call it MyExtendedBrowserControl.

Public

Class MyExtendedBrowserControl
' Based on WebBrowser
Inherits System.Windows.Forms.WebBrowser

' Define constants from winuser.h
Private Const WM_PARENTNOTIFY As Integer = &H210
Private Const WM_DESTROY As Integer = 2

'Define New event to fire
Public Event WBWantsToClose()

Protected Overrides Sub WndProc(ByRef m As Message)
    Select Case m.Msg
        Case WM_PARENTNOTIFY
            If (Not DesignMode) Then
                If (m.WParam = WM_DESTROY) Then
                    ' Tell whoever cares we are closing
                    RaiseEvent WBWantsToClose()
                End If
            End If
            DefWndProc(m)
        Case Else
            MyBase.WndProc(m)
    End Select
End Sub

End

Class

Now we have to get into the guts of the Form.  Although we dropped a WebBrowserControl on the form (and VB wired that up nicely for us) we REALLY want to create our new Control that extends the WebBrowser Control.

Choose File, Open from the Visual Studio menu and open the designer vb code (in this case Form1.Designer.vb).

Replace System.Windows.Forms.WebBrowser with the extended control MyExtendedBrowserControl.  There should be Two Places:

Me.WebBrowser1 = New VBCloseBrowser.ExtendedWebBrowser.ExtendWebBrowser

Friend WithEvents WebBrowser1 As VBCloseBrowser.ExtendedWebBrowser.ExtendWebBrowser

Save all the files and Build the project (you will see errors in the designers until you do build).

Now go to the design view of your Form.  Right Click on the Browser control and choose Properties…  Click on the Events Icon (the lightning bolt) and you will see at the bottom your new event WBWantsToClose.  Double click on that name and you will automatically add the handler for that event.  In my case, I simply want to close this form so I added Me.Close() in the handler.

Enjoy!