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 HotKey 48 { 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 KeyModifiers 68 { 69 None = 0, 70 Alt = 1, 71 Ctrl = 2, 72 Shift = 4, 73 WindowsKey = 8 74 } 75 }