WebBrowser "steals" KeyDown events from my form

10,078

Solution 1

This should solve your problem. It disabled the accelerator keys of the web browser.

webBrowser1.WebBrowserShortcutsEnabled = false;

You might want to explore whether you need IsWebBrowserContextMenuEnabled as well.

The following may also solve your problem if you need some accelerators keys to be active on the browser. However, this approach requires something to capture the focus. MessageBox.Show() and dialog.ShowDialog() can do the job

    private void DoSomething()
    {
        webBrowser1.PreviewKeyDown += new PreviewKeyDownEventHandler(webBrowser1_PreviewKeyDown);
    }
    private void webBrowser1_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e)
    {
        if (e.Control && e.KeyCode == Keys.O)
        {
            menuItem.PerformClick();
            // MessageBox.Show("Done");
        }
    }

Solution 2

You could override the ProcessCmdKey method:

protected override bool ProcessCmdKey(ref Meassage msg, Keys keyDaya)
{
    //Trap for Key down 

    return true; //false if you want to suppress the key press.
}
Share:
10,078
Juan
Author by

Juan

I'm a software developer, currently working on my personal project http://www.heliumscraper.com.

Updated on July 17, 2022

Comments

  • Juan
    Juan almost 2 years

    I have a WebBwoser inside a Form, and I want to capture the Ctrl+O key combination to use as a shortcut for a menu item. My problem is that if I click on the WebBrowser and I press Ctrl+O, an Internet Explorer dialog pops up, instead of doing what my menu item does. I have my Form's KeyPreview property set to true. Also, I added an event handler for the KeyDown event, but it stops getting called after I click the WebBrowser. How can I fix this?