Handling key events on WebBrowser control

Tony the Pony picture Tony the Pony · Mar 16, 2009 · Viewed 12.9k times · Source

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?

Answer

balexandre picture balexandre · Jun 17, 2009

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!
    }
}