David Amaral David Amaral - 1 month ago 23x
C# Question

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

I'm working on a

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


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)
    //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)
        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;