Handling key events on WebBrowser control

2019-02-07 02:52发布

问题:

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?

回答1:

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


回答2:

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


回答3:

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.