Reputation: 91
How can I determine what key user pressed, no matter where is the focus (as long as they are using the application)?
For example, they press "CTRL + Q" (quit) and the program exits no matter what.
Normally i'd have to go to the form event of KeyDown, and make that condition there. But what if the form wasn't focused? Then CTRL + Q wouldn't work.
How can I do this in windows forms applications? I'm sure it's simple but can't find a way.
Upvotes: 5
Views: 3934
Reputation: 7804
What you describe is commonly referred to as a system-wide hotkey.
Windows Forms does not inherently support system-wide hotkeys which means you will either need to manually register and manage each system-wide hotkey by means of the native RegisterHotkey
function or use a third-party library such as Shortcut.
Should you choose to manually register and manage each system-wide hotkey, here is an article and here is a screencast that should help you.
(Full disclosure: Shortcut is a project of mine, as is the screencast).
Upvotes: 4
Reputation: 103437
Your question is unclear - but given this quote:
How can I determine what key user pressed, no matter where is the focus (as long as they are using the application)?
I'm going to assume you are not looking for a system-global hotkey, just an application-global hotkey.
If you have only one form, you just need to set the KeyPreview property of your form to true.
This has the effect of sending all keypress events (KeyDown etc) to the form first, even if a control on the form has the focus.
Then you can simply implement your KeyDown handler as you mention in the question.
If you have multiple forms, then you might need to do this on each one.
Upvotes: 11