C#利用Api实现注册热键,附源码

利用api实现的注册热键,很久之前写的,发一下

using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;
using System.Runtime;
using System.Diagnostics;

namespace CrazyCoder.Common.Hook
{
    public class WinApi
    {
        [DllImport("user32.dll")]
        [return: MarshalAs(UnmanagedType.Bool)]
        public static extern bool RegisterHotKey(IntPtr hWnd, int id, uint fsModifiers, uint vk);

        [DllImport("user32.dll")]
        [return: MarshalAs(UnmanagedType.Bool)]
        public static extern bool UnregisterHotKey(IntPtr hWnd, int id);   
    }
    public class HotkeyHelper : IDisposable
    {
        public const int MOD_ALT = 0x1;
        public const int MOD_CONTROL = 0x2;
        public const int MOD_SHIFT = 0x4;
        public const int MOD_WIN = 0x8;
        public const int WM_HOTKEY = 0x312;

        private Dictionary<int, Hotkey> dicHotkeys;

        public HotkeyHelper()
        {
            dicHotkeys = new Dictionary<int, Hotkey>();
        }

        public bool RegisterHotKey(IntPtr hWnd, int id, uint fsModifiers, uint vk)
        {
            if (dicHotkeys.ContainsKey(id))
            {
                if (dicHotkeys[id].IsRegistered)
                {
                    UnregisterHotKey(dicHotkeys[id].HWnd, id);      // unregister firstly
                    dicHotkeys[id].IsRegistered = false;
                }
                dicHotkeys[id].HWnd = hWnd;                         // set the new hwnd (normally should be the same)
            }
            else
            {
                dicHotkeys.Add(id, new Hotkey(hWnd, false));
            }

            dicHotkeys[id].IsRegistered = WinApi.RegisterHotKey(hWnd, id, fsModifiers, vk);

            return dicHotkeys[id].IsRegistered;
        }

        private bool UnregisterHotKey(IntPtr hWnd, int id)
        {
            return WinApi.UnregisterHotKey(hWnd, id);
        }
   
        #region Hotkey Information
        class Hotkey
        {
            public Hotkey(IntPtr hWnd, bool isRegistered)
            {
                _HWnd = hWnd;
                _IsRegistered = isRegistered;
            }

            private IntPtr _HWnd;

            public IntPtr HWnd
            {
                get { return _HWnd; }
                set { _HWnd = value; }
            }

            private bool _IsRegistered;

            public bool IsRegistered
            {
                get { return _IsRegistered; }
                set { _IsRegistered = value; }
            }
        }
        #endregion

        #region IDisposable 成员

        public void Dispose()
        {
            foreach (int id in dicHotkeys.Keys)
            {
                if (dicHotkeys[id].IsRegistered)
                {
                    UnregisterHotKey(dicHotkeys[id].HWnd, id);
                }
            }
        }

        #endregion
    }
}

Tags:  C#热键

延伸阅读

最新评论

发表评论