1

I have shortcut keys in my WinForms application, but I want to process them AFTER the child controls.

I'm using KeyDown event in the main control and the 'g' key is used to display a grid. But in the edit box within the main control, when I press the 'g' key, the grid is displayed and the edit box receives the 'g'. If I set the 'g' key handled by the shortcut, the edit box does not receive the 'g' key.

=> my goal is to have all the keys handled first by the children and then by the main window, if it's not been handled yet.

Here is a code snippet:

public ShortCutManager(Control Control, string Title)
{
    _Control = Control;
    _Control.KeyDown += OnKeyDown;
}

private void OnKeyDown(object Sender, KeyEventArgs KeyEventArgs)
{               
    if (KeyEventArgs.KeyCode == Keys.G)
    {
        // What I need
        SendKeyEventToChildren(KeyEventArgs);

        if (KeyEventArgs.Handled == false)
        {
            DoShortcutCommand();
            KeyEventArgs.Handled = true;
        }
    }
}
sGlorz
  • 21
  • 5
  • What technology do you use (WPF, WinForms, ASP.NET, Silverlight, etc)? Tag a question with corresponding tag. – dvvrd Aug 14 '12 at 18:02

1 Answers1

1

What I'm doing is to override the ProcessDialogKey method in my form, similar to how it is described in this SO posting:

protected override bool ProcessDialogKey(Keys keyData)
{
    // Example: Handle Ctrl+C.
    if ((keyData & Keys.Control) == Keys.Control && (keyData & Keys.C) == Keys.C)
    {
        // Do some processing here...

        return true;
    }

    return base.ProcessDialogKey(keyData);
}
Community
  • 1
  • 1
Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
  • This implies that I implement the shortcuts in the control and not in a generic external class like it is now. – sGlorz Aug 16 '12 at 09:32
  • How about simply passing the `keyData` to your shortcut manager instance? – Uwe Keim Aug 16 '12 at 09:55
  • Ok, I've made a test and it does not work. When a key is entered, it is called 2 times (Key up & Key down) and when I call base.ProcessDialogKey(keyData) it's always false when I press the G key, even if I'm in a edit box. Moreover, " This method is called during message preprocessing to handle dialog characters, such as TAB, RETURN, ESC, and arrow keys". So It won't return any answer for "regular" keys. – sGlorz Aug 16 '12 at 13:53
  • There is also [`IsInputKey`](http://msdn.microsoft.com/en-us/library/system.windows.forms.control.isinputkey.aspx) which might help to count additional keys as dialog keys. – Uwe Keim Aug 16 '12 at 14:08
  • IsInputKey is called by some of the controls (like TextBox), and it is not called in the main form, I can't use it. – sGlorz Aug 16 '12 at 14:29