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:
Private Sub WebBrowser1_DocumentCompleted(ByVal sender As System.Object, ByVal e As Windows.Forms.WebBrowserDocumentCompletedEventArgs) Handles WebBrowser1.DocumentCompleted
Dim document As HtmlDocument = WebBrowser1.Document
'Attach KeyDown event handler
AddHandler document.Body.KeyDown, New HtmlElementEventHandler(AddressOf WebBrowser1_KeyDown)
'Attach MouseDown event handler
AddHandler document.Body.MouseDown, New HtmlElementEventHandler(AddressOf WebBrowser1_MouseDown)
End Sub
Private Sub WebBrowser1_KeyDown(ByVal sender As Object, ByVal e As HtmlElementEventArgs)
If e.CtrlKeyPressed And e.KeyPressedCode <> Keys.ControlKey Then
'CTRL+SomeKey was pressed.
Debug.WriteLine("CTRL + " & Chr(e.KeyPressedCode))
ElseIf e.ShiftKeyPressed And e.KeyPressedCode <> Keys.ShiftKey Then
'SHIFT+SomeKey was pressed.
Debug.WriteLine("SHIFT + " & Chr(e.KeyPressedCode))
ElseIf e.AltKeyPressed AndAlso e.KeyPressedCode <> Keys.Alt Then
'ALT+SomeKey was pressed.
Debug.WriteLine("ALT + " & Chr(e.KeyPressedCode))
Else
'SomeKey was pressed without any modifier keys.
Debug.WriteLine(Chr(e.KeyPressedCode))
End If
End Sub
Private Sub WebBrowser1_MouseDown(ByVal sender As Object, ByVal e As HtmlElementEventArgs)
If e.MouseButtonsPressed = Windows.Forms.MouseButtons.Left Then
'MouseDown event
Debug.WriteLine("MouseDown at " & e.MousePosition.X & "," & e.MousePosition.Y)
End If
End Sub
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.
Enjoy ![]()
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.).
Fortunately the HTMLDocument class provides ways to hook keyboard and mouse events to the document it is hosting. It is almost same as javascript events but with and added advantage of hooking up with managed code in our application.
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

November 22, 2010 at 5:56 pm
Thank you dude!:)
It really helped me)
from BMSTU.
January 1, 2011 at 7:43 pm
[…] vuoi intercettare l'evento KeyDown o KeyUp direttamente nel WebBrowser, come spiegato anche qui: Easy way to add Keyboard and Mouse events to WebBrowser control Pradeep1210's Blog , dovrai aggiungere manualmente la gestione dell'evento .Document.Body.KeyUp. Per farlo, […]
February 6, 2011 at 8:51 pm
hi pradeep,
i m trying to simulate a button click inside the webbrowser control, do you have any idea it can be done?
I found a relative article at:
http://www.geekpedia.com/code139_Simulate-Mouse-Click-On-WebBrowser-Control.html
but in that i need to manually give the X and Y coordinates. Any idea of getting the button dynamically?
if not then is there any way to get X and Y coordinates of a mouse’s current position in .net?
February 6, 2011 at 8:57 pm
It should be easy one line code unless you need something specialized:
WebBrowser1.Document.GetElementById("YourButton").InvokeMember("click")February 6, 2011 at 9:17 pm
i got the mouse position from Cursor.Position.X
Can i simulate TYPING in someway?
February 6, 2011 at 9:20 pm
well previously i was using Watin and it was going fine..but now there’s a javaApplet object in browser.and i can’t get it’s internal TextBox and Buttons.
all i can think is of getting their position and simulating them through window handles.
July 1, 2011 at 9:22 pm
how would you go about using xButton1 and xButton2 with this? i tried using Windows.Forms.MouseButtons.XButton1
instead of Windows.Forms.MouseButtons.Left but nothing happens, im trying to figure a way to make the 4th and 5th mouse buttons to do WebBrowser1.GoBack() and WebBrowser1.GoForward() with little luck
July 2, 2011 at 1:41 am
Not sure about this. I don’t have a mouse with more than 3 buttons here, so I can’t even experiment around and suggest you any solutions. 😦
Have a look at this link. It might be of some use:
http://msdn.microsoft.com/en-us/library/system.windows.forms.htmlelementeventargs.mousebuttonspressed.aspx
July 2, 2011 at 1:45 am
What happens if you handle the HtmlDocument.Click event instead of MouseUp/MouseDown?
December 7, 2011 at 3:49 am
How to simulate mouse click a link in webbrowser control? I try use linkelement.InvokeMember(“click”), .InvokeMember(“onclick”), .RaiseEvent(“click”)… but not work correctly.
Thanks!
December 7, 2011 at 8:32 am
Sorry, this article doesn’t deal with simulating mouse clicks. It deals with attaching mouse event to the web-browser control.
January 15, 2012 at 3:17 pm
ok, im tired play with this..you can try your self on this, its totally useless doing such a thing
i add the following control in my form
_________________________________________
Public Class Form1
Dim config As String = My.Computer.FileSystem.CurrentDirectory & “/config.ini”
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
WebBrowser1.Navigate(“C:/WINDOWS/”)
End Sub
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
End
End Sub
Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click
WebBrowser1.Navigate(“www.google.com”)
End Sub
End Class
_________________________________________
then set “IsContextMenuEnable” to false on the webbrowser1 control
after build it, i notice that i cant right click anymore on the webbrowser when its was on google.com
and i still can right click on the webbrowser when its was on my “C:/WINDOWS/”
my question, how do i disable right click all over my form or in just my webbrowser?
im really appreciate if someone can show me the way
December 8, 2012 at 3:26 am
[…] Its similar to this post I found except I want a specific html 5 element in the html document loaded in the browser when clicked: https://pradeep1210.wordpress.com/2010/03/19/easy-way-to-add-keyboard-and-mouse-events-to-webbrowser-… […]
February 7, 2013 at 8:18 am
gr8…. thanx a lot…… i was trying this since long…….. thanx again
March 23, 2013 at 10:09 am
Excellent review I began with Green Smoke and I’ve really already been enjoying them. Thanks!
May 20, 2013 at 5:42 am
nice article, is it also possible to catch the click event when I load an Excel file.. the click event would fire every time i clicked on a cell…
May 20, 2013 at 2:12 pm
Certainly not with the installed Excel application. But it might be possible with Excel Web App with some hacks I’m not sure of.
May 21, 2013 at 9:07 am
if it would not be too much, having that article would be great. thank you
August 24, 2013 at 1:50 am
Aren’t you re-re-re-re-re-adding the handler code, every time the webBrowser completes a loading event?
September 16, 2013 at 7:28 am
No, the object will get destroyed whenever a new document is loaded, so does the handler. Whenever a new document is loaded, the DocumentCompleted event is fired.
August 28, 2013 at 4:41 am
how about capturing F1 – F12 keys?
it seems like that e.KeyPressedCode do not recognize F1-F12 keys
January 16, 2015 at 1:18 pm
I used this code to catch 2 keys: ESC and F11 keys. They work 100% to “exit my prg” and “make it full screen”.
Unfortunately, it only works until I hit F5 (refresh). After I refresh… then my 2 keys never work again.
January 19, 2015 at 5:32 am
It won’t work and you probably already know the reason why 🙂
When you press F5 (or click the refresh button on toolbar), the whole page is reloaded. Anything that was there on the page earlier is wiped out; the page is loaded from scratch.
April 5, 2016 at 12:19 pm
… so how can that be fixed???? (Why do people tell “the problem” but never tell how to FIX the problem???)
April 5, 2016 at 4:53 pm
I think the only way to get around this problem is to not let the page refresh. Instead put your whole page or relevent parts of the page in a container and do partial page (AJAX) calls to load it. AJAX calls won’t load the document from scratch, so that would work.
April 5, 2016 at 12:18 pm
> 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.
Won’t that re-re-re-re-recreate the handlers many times over? Or does that not matter?
April 5, 2016 at 4:48 pm
The document is unloaded every time there is a new page load, so it really doesn’t matter.