Handling key events on WebBrowser control

心已入冬 提交于 2019-11-30 09:33:19

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

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

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.

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