Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handling key events on WebBrowser control

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?

like image 263
Tony the Pony Avatar asked Mar 16 '09 06:03

Tony the Pony


3 Answers

you have the PreviewKeyDown event just hook it up.

private void wb_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e)
{
    // your code handling the keys here, like:
    if (e.Control && e.KeyCode == Keys.C)
    {
        // Do something funny!
    }
}
like image 138
balexandre Avatar answered Nov 18 '22 06:11

balexandre


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:

Protected Overrides Function ProcessCmdKey(ByRef msg As Message, keyData As Keys) As Boolean

    If keyData <> Keys.Enter Then Return MyBase.ProcessCmdKey(msg, keyData)
    Return True

End Function
like image 36
nuander Avatar answered Nov 18 '22 07:11

nuander


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.

webBrowser.Document.Body.KeyDown += MyKeyDownHandler;
...
private void MyKeyDownHandler(object sender, HtmlElementEventArgs e)
{
    // Set e.ReturnValue false if you want to cancel the key press
}

I think the handler has to be added after the document has loaded, e.g. in the DocumentCompleted event handler.

like image 44
JonP Avatar answered Nov 18 '22 06:11

JonP