WebBrowser “steals” KeyDown events from my form

2019-06-21 22:29发布

问题:

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?

回答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");
        }
    }


回答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.
}