.NET framework does not by default provide classes/methods for creating global hotkeys in our .NET applications. A hotkey can be defined as a particular key combination pressing of which triggers a event in our application even if user is not actively working on our app. For achieving this, we’ll have to call into win32 api functions. Though .NET framework makes this work relatively easy, still calling into managed dlls and wrapping them in .NET classes and constants is not a trivial task. To avoid all this, we can use an open source, LGPL licensed sourceforge project Managed Win API
Just download the binary dlls and reference the ManagedWinapi.dll from your WinForms project. After this, we can use Hotkey class inside the ManagedWinaapi dll to create global hotkeys.
Now, add the following declaration in the form class.
ManagedWinapi.Hotkey hotkey = new ManagedWinapi.Hotkey();
Now, set up the hot key when the form loads.
hotkey.KeyCode = Keys.A;
hotkey.Ctrl = true;
hotkey.HotkeyPressed += new EventHandler(hotkey_HotkeyPressed);
Now, hotkey is setup properlly, hotkey_HotkeyPressed event handler will get called when user presses Ctrl+A. However, there is one more step, enabling the hotkey. For enabling the hotkey and to start trapping hotkey presses, set the Enabled property to true.
hotkey.Enabled=true;
You can stopp trapping the hot key by setting the Enabled property to false. Handle the HotkeyPressed event of the Hotkey class for executing code when hotkey is pressed.
void hotkey_HotkeyPressed(object sender, EventArgs e)
{
// do the stuff here.
}