Search code examples
c#winformsbrowserkeyblock

WinForms WebBrowser blocking ProcessCmdKey


I've got a simple Windows Forms application that's nothing more than a Form that contains a WebBrowser.

I'm overriding the ProcessCmdKey method and it works fine. But, while the WebBrowser has the focus, ProcessCmdKey is still called, however, it no longer picks up key codes.

protected override bool ProcessCmdKey(ref Message msg, Keys keyData){

    //When webbrowser has focus, only control or S are found - not both.
    if(keyData==(Keys.Control|Keys.S)){
        //Do things here.
        return true;
    }

    return false;
}

Solution

  • Did you try overriding the WebBroswer's ProcessCmdKey... I vaguely recall the browser does something funky with bubbing-up events... to do with security. Yeah, here it is:

    http://msdn.microsoft.com/en-us/library/system.windows.forms.control.processcmdkey.aspx Says:

    This method is called during message preprocessing to handle command keys. Command keys are keys that always take precedence over regular input keys. Examples of command keys include accelerators and menu shortcuts. The method must return true to indicate that it has processed the command key, or false to indicate that the key is not a command key. This method is only called when the control is hosted in a Windows Forms application or as an ActiveX control.

    The ProcessCmdKey method first determines whether the control has a ContextMenu, and if so, enables the ContextMenu to process the command key. If the command key is not a menu shortcut and the control has a parent, the key is passed to the parent's ProcessCmdKey method. The net effect is that command keys are "bubbled" up the control hierarchy. In addition to the key the user pressed, the key data also indicates which, if any, modifier keys were pressed at the same time as the key. Modifier keys include the SHIFT, CTRL, and ALT keys.

    I don't think it'll let you intercept browser keys at the form level... I think the events are eaten by the WebBrowser control.

    Cheers. Keith.


    EDIT:

    http://msdn.microsoft.com/en-us/library/system.windows.forms.keys.aspx says:

    KeyCode The bitmask to extract a key code from a key value. Modifiers The bitmask to extract modifiers from a key value.

    and the example contains the lines:

    if(e.KeyCode != Keys.Back)
    
    if (Control.ModifierKeys == Keys.Shift) {
    

    So I guess you need to bit-twiddle that key into it's component parts.