Subclass the Microsoft Web Browser control

Forms and Controls

Version Compatibility: Visual Basic 6, Visual Basic 5

More information:
Subclassing the Microsoft Web Browser control is not as easy as it might seem at first. There are two problems that must be overcome.

First, Microsoft doesn't want you to do this at all, so they make the hWnd property of the control unreadable. In order to get the hWnd of the web browser control, you have to take the webBrowser.Parent.hWnd value and call EnumChildWindows. Once you find the right window by class name, you can get the hWnd of the control itself.

The second problem is that the window you need to subclass does not exist until you have loaded a web page into the control. To get around this issue, you need to place the following line of code into the following event:

Private Sub webBrowser_BeforeNavigate2()
    'Only hook the window procedure once
    If Not HookedWebBrowser Then Call HookWebBrowser(Me.webBrowser.Parent.hwnd)
End Sub

Now you can trap the window messages sent to the web browser control just like you would for a form or other control. My example here disables the right-mouse button so that users can't get the pop-up menu in my application.

Instructions: Copy the declarations and code below and paste directly into your VB project.