Handling key events on WebBrowser control

自作多情 提交于 2019-11-29 14:55:28

问题


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.



来源:https://stackoverflow.com/questions/649441/handling-key-events-on-webbrowser-control

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!