tags:

views:

1453

answers:

4
A: 

This is probably not the best way of doing it, but the first way that comes to mind.

In your forms constructor, after you call InitializeComponent(); do something like this:

            foreach (Control control in this.Controls)
            {
                control.PreviewKeyDown += new PreviewKeyDownEventHandler(HandlePreviewKeyDown);
            }

I THINK that should do the trick. In your HandlePreviewKeyDown method you can then do your work and it should trigger regardless of which control has focus.

BFree
+1  A: 

PreviewKeyDown only works when the control has focus. It sounds like you should look into an application level hook for a special shortcut keys. You'll have to do it with a P/Invoke. SetWindowsHookEx on pinvoke.net is a good place for an example. Here's a MS KB article about a mouse hook in c#, which appears to be expanded to a keyboard hook in this article.

Factor Mystic
A: 

The hidden menu you are using works fine for shortcuts that are valid menu item shortcuts, but if you want to use any key as a shortcut (such as Page Up/Page Down), you'll need a different trick.

Another way to do this that doesn't involve P/Invoke is to set the Form.KeyPreview property of your form to true. This will cause all key presses to be sent to the form first, regardless of which control has focus. You can then override OnKeyDown, OnKeyPress, and/or OnKeyUp to handle the key press before any of your controls.

alabamasucks
+1  A: 

We ended up doing this:

I found a workaround for this by setting up a hidden menu item by setting:

ToolStripMenuItem.Visible = false

(Thanks to this article).

It appears that the Main Menu of a form always gets searched for your shortcut key combination. This works regardless of whick control has focus

Byron Ross
+1 pretty hack :)
BlueRaja - Danny Pflughoeft