/// <summary> /// Defines a system-wide hot key. /// </summary> /// <param name="hWnd">A handle to the window that will receive WM_HOTKEY messages generated by the hot key. If this parameter is NULL, WM_HOTKEY messages are posted to the message queue of the calling thread and must be processed in the message loop.</param> /// <param name="id">The identifier of the hot key. If the hWnd parameter is NULL, then the hot key is associated with the current thread rather than with a particular window. If a hot key already exists with the same hWnd and id parameters, see Remarks for the action taken.</param> /// <param name="fsModifiers">The keys that must be pressed in combination with the key specified by the uVirtKey parameter in order to generate the WM_HOTKEY message. The fsModifiers parameter can be a combination of the following values.</param> /// <param name="vk">The virtual-key code of the hot key</param> /// <returns>If the function succeeds, the return value is nonzero.</returns> [DllImport("user32.dll", CharSet = CharSet.Auto, ExactSpelling = true)] public static extern bool RegisterHotKey(IntPtr hWnd, int id, Modifiers fsModifiers, Keys vk);//注册函数 /// <summary> /// Frees a hot key previously registered by the calling thread. /// </summary> /// <param name="hWnd">A handle to the window associated with the hot key to be freed. This parameter should be NULL if the hot key is not associated with a window.</param> /// <param name="id">The identifier of the hot key to be freed.</param> /// <returns></returns> [DllImport("user32.dll", CharSet = CharSet.Auto, ExactSpelling = true)] public static extern bool UnregisterHotKey(IntPtr hWnd, int id);//接触注册函数 public const int WM_HOTKEY = 0x0312; public Form1() { InitializeComponent(); } private void btnUnregister_Click(object sender, EventArgs e) { UnregisterHotKey(this.Handle, 8080); //8080:热键的标志id } private void btnRegister_Click(object sender, EventArgs e) { RegisterHotKey(this.Handle, 8080, Modifiers.MOD_CONTROL, Keys.C); //8080:热键的标志id 2:crtl A: C } protected override void WndProc(ref Message m) { switch (m.Msg) { case WM_HOTKEY: //window消息定义的註冊的热键消息 if (m.WParam.Equals((IntPtr)8080)) MessageBox.Show("你按了ctrl+C"); break; } base.WndProc(ref m); } } public enum Modifiers : uint { /// <summary> /// Either ALT key must be held down. /// </summary> MOD_ALT = 0x0001, /// <summary> /// Either CTRL key must be held down. /// </summary> MOD_CONTROL = 0x0002, /// <summary> /// Changes the hotkey behavior so that the keyboard auto-repeat does not yield multiple hotkey notifications. /// Windows Vista and Windows XP/2000: This flag is not supported. /// </summary> MOD_NOREPEAT = 0x4000, /// <summary> /// Either SHIFT key must be held down. /// </summary> MOD_SHIFT = 0x0004, /// <summary> /// Either WINDOWS key was held down. These keys are labeled with the Windows logo. Keyboard shortcuts that involve the WINDOWS key are reserved for use by the operating system. /// </summary> MOD_WIN = 0x0008 }