Handle Tab Key Press on WebBrowser Control and Prevent Switching between Html Elements

半城伤御伤魂 提交于 2019-12-02 01:23:40

You can hanlde KeyDown event of WebBrowser.Document.Body and check if the down key is Tab prevent default action bu setting e.ReturnValue = false; and perform your desired operation.

You can use HtmlElementEventArgs properties to know about pressed key and the state of the modifier keys.

private void Form1_Load(object sender, EventArgs e)
{
    webBrowser1.Navigate("http://www.google.com");
    //Attach a handler to DocumentCompleted
    webBrowser1.DocumentCompleted += webBrowser1_DocumentCompleted;
}

void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
    //Attach a handler to Body.KeyDown when the document completed
    webBrowser1.Document.Body.KeyDown += Body_KeyDown;
}

void Body_KeyDown(object sender, HtmlElementEventArgs e)
{
    if(e.KeyPressedCode==(int)Keys.Tab)
        MessageBox.Show("Tab Handled");
    //Prevent defaut behaviour
    e.ReturnValue = false;
}

You can also limit above code to a single element:

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