windhuan
11/29/2017 - 9:41 AM

WPF 注册系统热键

    internal static class HotKeyManager
    {
        private static IntPtr hwnd = IntPtr.Zero;
        private static Dictionary<int, Action> hotkeyAction = new Dictionary<int, Action>();

        public static void Init()
        {
            var source = HwndSource.FromHwnd(new WindowInteropHelper(App.Current.MainWindow).Handle);
            source.AddHook(WndProc);
            hwnd = source.Handle;
        }

        public static void UnInit()
        {
            var keys = hotkeyAction.Keys.ToList();
            foreach (var id in keys)
            {
                UnRegister(id);
            }
        }

        public static bool Register(int id, KeyModifiers control, Keys vk, Action action)
        {
            if (hwnd == IntPtr.Zero)
            {
                throw new Exception("No Init");
            }
            var isOk = Win32.RegisterHotKey(hwnd, id, (uint)control, vk);
            if (isOk)
            {
                hotkeyAction.Add(id, action);
                return true;
            }
            else
            {
                return false;
            }
        }

        public static void UnRegister(int id)
        {
            if (hwnd != IntPtr.Zero)
            {
                if (hotkeyAction.ContainsKey(id))
                {
                    Win32.UnregisterHotKey(hwnd, id);
                    hotkeyAction.Remove(id);
                }
            }
        }

        private static IntPtr WndProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled)
        {
            if (msg == 0x0312)
            {
                if (hotkeyAction.ContainsKey(wParam.ToInt32()))
                {
                    hotkeyAction[wParam.ToInt32()]();
                }
            }
            return IntPtr.Zero;
        }
    }