1 public partial class Form2 : Form 2 { 3 [DllImport("user32")] 4 public static extern bool RegisterHotKey(IntPtr hWnd, int id, uint control, Keys vk); 5 //解除註冊熱鍵的api 6 [DllImport("user32")] 7 public static extern bool UnregisterHotKey(IntPtr hWnd, int id); 8 const int WM_HOTKEY = 0x0312; 9 public Form2()10 {11 InitializeComponent();12 }13 14 private void Form2_Load(object sender, EventArgs e)15 {16 //100為代號17 HotKey.RegisterHotKey(Handle, 100, HotKey.KeyModifiers.Ctrl, Keys.Space);18 }19 20 private void Form1_FormClosed(object sender, FormClosedEventArgs e)21 {22 //100為代號23 HotKey.UnregisterHotKey(this.Handle, 100);24 }25 26 protected override void WndProc(ref Message m)27 {28 switch (m.Msg)29 {30 case WM_HOTKEY:31 {32 switch (m.WParam.ToInt32())33 {34 case 100:35 {36 SendKeys.Send("^+");//SHIFT:+ CTRL:^37 break;38 }39 }40 break;41 }42 }43 base.WndProc(ref m);44 } 45 }46 47 public class HotKey48 {49 //如果函數執行成功,傳回值不為0。 50 //如果函數執行失敗,傳回值為0。要得到擴充錯誤資訊,調用GetLastError。 51 [DllImport("user32.dll", SetLastError = true)]52 public static extern bool RegisterHotKey(53 IntPtr hWnd, //要定義熱鍵的視窗的控制代碼 54 int id, //定義熱鍵ID(不能與其它ID重複) 55 KeyModifiers fsModifiers, //標識熱鍵是否在按Alt、Ctrl、Shift、Windows等鍵時才會生效 56 Keys vk //定義熱鍵的內容 57 );58 59 [DllImport("user32.dll", SetLastError = true)]60 public static extern bool UnregisterHotKey(61 IntPtr hWnd, //要取消熱鍵的視窗的控制代碼 62 int id //要取消熱鍵的ID 63 );64 65 //定義了輔助鍵的名稱(將數字轉變為字元以便於記憶,也可去除此枚舉而直接使用數值) 66 [Flags()]67 public enum KeyModifiers68 {69 None = 0,70 Alt = 1,71 Ctrl = 2,72 Shift = 4,73 WindowsKey = 874 }75 }