Today I dirtied my hands researching about how to add keyboard and mouse events to the .NET WebBrowser control. It is not as straight-forward as it might look at first instance. The WebBrowser control suppresses these events in one way or the other and you can’t trap them at the control level or at form level (by setting KeyPreview to True etc.).
However there are still ways to trap the mouse and keyboard events in the WebBrowser control. For this demo and to keep the code short, I’ll show only two events – the KeyDown event and the MouseDown event. But you can add any of the other events you wish to in just the same way.
Start Visual Studio and create a new VB.NET Windows Forms application.
Add a WebBrowser control and a Button to your form.
Add the following code:
Run the code. Click the Button. This will open the Google website and add the mouse and keyboard event handlers.
Now press any key / key-combination or click anywhere in the WebBrowser control and watch is printed in the Debug window.
How the Code Works
The WebBrowser control does not expose the mouse and keyboard events directly. Even if you build your own control inherited from the WebBrowser class or the WebBrowserBase class, the events have been cleverly hidden. There might be some tricky way to expose the events I never know of (e.g. overriding the WndProc etc.).
Always take care to attach the event handlers when the page has fully loaded in your WebBrowser control. Otherwise, you will experience problems. So the best place to do that is the DocumentCompleted event.
References & Further Readings
Keywords: WebBrowser Control, Keyboard events, mouse events, KeyUp, KeyDown, KeyPress, MouseDown, MouseUp, MouseMove, HtmlElementEventHandler, HtmlDocument