Files
GeekDesk/Util/HotKey.cs

98 lines
2.8 KiB
C#
Raw Normal View History

2021-05-12 10:00:12 +08:00
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Windows;
using System.Windows.Input;
using System.Windows.Interop;
2021-05-19 17:31:28 +08:00
/// <summary>
/// 热键注册
/// </summary>
2021-05-12 10:00:12 +08:00
namespace GeekDesk.Util
{
class Hotkey
{
#region api
[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool RegisterHotKey(IntPtr hWnd, int id, HotkeyModifiers fsModifiers, uint vk);
[DllImport("user32.dll")]
static extern bool UnregisterHotKey(IntPtr hWnd, int id);
#endregion
/// <summary>
/// 注册快捷键
/// </summary>
/// <param name="window">持有快捷键窗口</param>
/// <param name="fsModifiers">组合键</param>
/// <param name="key">快捷键</param>
/// <param name="callBack">回调函数</param>
public static int Regist(IntPtr windowHandle, HotkeyModifiers fsModifiers, Key key, HotKeyCallBackHanlder callBack)
2021-05-12 10:00:12 +08:00
{
var _hwndSource = HwndSource.FromHwnd(windowHandle);
2021-05-12 10:00:12 +08:00
_hwndSource.AddHook(WndProc);
int id = keyid++;
var vk = KeyInterop.VirtualKeyFromKey(key);
keymap.Add(id, callBack);
if (!RegisterHotKey(windowHandle, id, fsModifiers, (uint)vk)) throw new Exception("RegisterHotKey Failed");
2021-06-02 17:34:02 +08:00
return id;
2021-05-12 10:00:12 +08:00
}
/// <summary>
/// 快捷键消息处理
/// </summary>
static IntPtr WndProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled)
{
if (msg == WM_HOTKEY)
{
int id = wParam.ToInt32();
if (keymap.TryGetValue(id, out var callback))
{
callback();
}
}
return IntPtr.Zero;
}
/// <summary>
/// 注销快捷键
/// </summary>
/// <param name="hWnd">持有快捷键窗口的句柄</param>
/// <param name="callBack">回调函数</param>
public static void UnRegist(IntPtr hWnd, HotKeyCallBackHanlder callBack)
{
List<int> list = new List<int>(keymap.Keys);
for (int i=0; i < list.Count; i++)
2021-05-12 10:00:12 +08:00
{
if (keymap[list[i]] == callBack)
{
UnregisterHotKey(hWnd, list[i]);
keymap.Remove(list[i]);
}
2021-05-12 10:00:12 +08:00
}
}
const int WM_HOTKEY = 0x312;
static int keyid = 10;
2021-06-02 17:34:02 +08:00
public static Dictionary<int, HotKeyCallBackHanlder> keymap = new Dictionary<int, HotKeyCallBackHanlder>();
2021-05-12 10:00:12 +08:00
public delegate void HotKeyCallBackHanlder();
}
2021-05-31 21:54:10 +08:00
public enum HotkeyModifiers
2021-05-12 10:00:12 +08:00
{
MOD_ALT = 0x1,
MOD_CONTROL = 0x2,
MOD_SHIFT = 0x4,
MOD_WIN = 0x8
}
}