Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WebBrowser "steals" KeyDown events from my form

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?

like image 420
Juan Avatar asked Mar 02 '11 08:03

Juan


2 Answers

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");
        }
    }
like image 196
Fun Mun Pieng Avatar answered Oct 24 '22 12:10

Fun Mun Pieng


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.
}
like image 36
WillDud Avatar answered Oct 24 '22 11:10

WillDud