Home
Manage Your Code
Snippet: HotKey (C#)
Title: HotKey Language: C#
Description: Create global hot key Views: 6265
Author: Dmitry Starchuk Date Added: 3/30/2006
Copy Code  
1	public partial class autokey : Form
2				   {
3					   const int HOTKEY_ID = 31197;    //any number to be used as an id within this app
4					   const int WM_HOTKEY = 0x0312;
5
6					   public enum KeyModifiers        //enum to call 3rd parameter of RegisterHotKey easily
7					   {
8						   None = 0,
9						   Alt = 1,
10						   Control = 2,
11						   Shift = 4,
12						   Windows = 8
13					   }
14					   //API Imports
15					   [DllImport("user32.dll", SetLastError = true)]
16					   public static extern bool RegisterHotKey(
17						   IntPtr hWnd, // handle to window    
18						   int id, // hot key identifier    
19						   KeyModifiers fsModifiers, // key-modifier options    
20						   Keys vk    // virtual-key code    
21						   );
22
23					   [DllImport("user32.dll", SetLastError = true)]
24					   public static extern bool UnregisterHotKey(
25						   IntPtr hWnd, // handle to window    
26						   int id      // hot key identifier    
27						   );
28
29					   public autokey()	//construct the class
30					   {
31						   InitializeComponent();
32						   //set hotkey on key F11 (return value here only for debugging)
33						   bool bcheck = RegisterHotKey(Handle, HOTKEY_ID, KeyModifiers.None, Keys.F11);
34					   }
35
36					   private void Form_Closed(object sender, FormClosedEventArgs e)
37					   {
38						   //reset hotkey if exit  (return value here only for debugging)
39						   bool bcheck = UnregisterHotKey(Handle, HOTKEY_ID);
40					   }
41
42					   //having registered a hotkey the thread that registered it receives a WM_HOTKEY message upon the keypress which has to be caught by overwriting the WndProc method
43					   protected override void WndProc(ref Message msg)
44					   {
45						   // Listen for operating system messages.
46						   switch (msg.Msg)
47						   {
48							   case WM_HOTKEY:
49								   // this is the block the app turns in if the hotkey has been pressed
50								   //so do your f@cking hotkey stuff here :-D
51								   break;
52						   }
53						   base.WndProc(ref msg);
54					   }
55
56				   }