Reputation: 141
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?
Upvotes: 2
Views: 1146
Reputation: 125197
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;
Upvotes: 2