WPF 全局快捷键
示例:按ESC快捷键
#region 注册全局快捷键
//引入Winows API
[DllImport("user32.dll")]
private static extern bool RegisterHotKey(IntPtr hWnd, int id, uint fsModifiers, uint vk);
[DllImport("user32.dll")]
private static extern bool UnregisterHotKey(IntPtr hWnd, int id);
private const int HOTKEY_ID = 9527;
//Modifiers:
private const uint MOD_NONE = 0x0000; //(none)
private const uint MOD_ALT = 0x0001; //ALT
private const uint MOD_CONTROL = 0x0002; //CTRL
private const uint MOD_SHIFT = 0x0004; //SHIFT
private const uint MOD_WIN = 0x0008; //WINDOWS
//CAPS LOCK:
private const uint VK_CAPITAL = 0x14;
private IntPtr _windowHandle;
private HwndSource _source;
protected override void OnSourceInitialized(EventArgs e)
{
base.OnSourceInitialized(e);
_windowHandle = new WindowInteropHelper(this).Handle;
_source = HwndSource.FromHwnd(_windowHandle);
_source.AddHook(HwndHook);
//RegisterHotKey(_windowHandle, HOTKEY_ID, 第一个键, 第二个键);
RegisterHotKey(_windowHandle, HOTKEY_ID, 0, 0x1B);
}
private IntPtr HwndHook(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled)
{
const int WM_HOTKEY = 0x0312;//热键消息
switch (msg)
{
case WM_HOTKEY:
switch (wParam.ToInt32())
{
case HOTKEY_ID:
int vkey = (((int)lParam >> 16) & 0xFFFF);
if (vkey == 0x1B)
{
this.Topmost = false;
this.WindowStyle = System.Windows.WindowStyle.None;
this.WindowState = System.Windows.WindowState.Normal;
}
handled = true;
break;
}
break;
}
return IntPtr.Zero;
}
protected override void OnClosed(EventArgs e)
{
_source.RemoveHook(HwndHook);
UnregisterHotKey(_windowHandle, HOTKEY_ID);
base.OnClosed(e);
}
#endregion

浙公网安备 33010602011771号