I am using the WebBrowser
control in a C# application and want to handle all key events while the WebBrowser
has the focus, regardless what individual content element (input field, link, etc.) is focused. I tried to simply add an event handler to browser controls KeyDown
event, but this does not work. I don't want to explicitly hook a handler to each focusable HtmlElement
.
How can I receive all key events before they are passed to the browser or its content elements?
If you want to do something like circumventing the Enter key in the WebBrowser control you are out of luck because there is no KeyPress or KeyDown events for the control. KeyPreviewDownEventArgs does not provide any way to circumvent a key press. The only way to do that is to overide the ProcessCmdKey function of the form that hosts the control. For Example:
you have the PreviewKeyDown event just hook it up.
You can add key handlers to the Body element of the loaded document. By default this catches the same event occurring in any child element of the body element.
I think the handler has to be added after the document has loaded, e.g. in the DocumentCompleted event handler.