David Amaral David Amaral - 3 months ago 57
C# Question

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

I'm working on a

WebBrowser
Control app and I need to handle Tab key press and prevent switching between html element. I cannot use
KeyDown
events because
WebBrowser
Control doesn't support those. So it seems I have to use
PreviewKeyDown
or something similar. Any idea on how can I program this?

Answer

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