Handle Tab键按下WebBrowser控件并防止在Html元素之间切换

时间:2016-08-31 14:32:10

标签: c# winforms webbrowser-control

我正在使用WebBrowser控制应用,我需要处理 Tab 按键并阻止在html元素之间切换。我无法使用KeyDown个事件,因为WebBrowser Control并不支持这些事件。所以我似乎必须使用PreviewKeyDown或类似的东西。关于如何编程的任何想法?

1 个答案:

答案 0 :(得分:2)

您可以查看KeyDown WebBrowser.Document.Body事件并检查向下键是否为 Tab 阻止默认操作设置e.ReturnValue = false;并执行您想要的操作。< / p>

您可以使用HtmlElementEventArgs属性了解按下的键和修改键的状态。

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

您还可以将上述代码限制为单个元素:

webBrowser1.Document.GetElementById("someid").KeyDown += Body_KeyDown;
相关问题