C#實現全局快捷鍵功能

在c#中使用全局快捷鍵

由於.net並沒有提供快捷鍵的庫,所以要使用該功能得通過api實現。

在winapi中,註冊和註銷全局快捷鍵分別是通過RegisterHotKeyUnregisterHotKey函數實現。在c#中直接使用該api顯得不夠簡潔,這裡我提供瞭一個友好點的封裝。

代碼如下:

    static class Hotkey
    {
        #region 系統api
        [DllImport("user32.dll")]
        [return: MarshalAs(UnmanagedType.Bool)]
        static extern bool RegisterHotKey(IntPtr hWnd, int id, HotkeyModifiers fsModifiers, Keys vk);

        [DllImport("user32.dll")]
        static extern bool UnregisterHotKey(IntPtr hWnd, int id);
        #endregion

        /// <summary> 
        /// 註冊快捷鍵 
        /// </summary> 
        /// <param name="hWnd">持有快捷鍵窗口的句柄</param> 
        /// <param name="fsModifiers">組合鍵</param> 
        /// <param name="vk">快捷鍵的虛擬鍵碼</param> 
        /// <param name="callBack">回調函數</param> 
        public static void Regist(IntPtr hWnd, HotkeyModifiers fsModifiers, Keys vk, HotKeyCallBackHanlder callBack)
        {
            int id = keyid++;
            if (!RegisterHotKey(hWnd, id, fsModifiers, vk))
                throw new Exception("regist hotkey fail.");
            keymap[id] = callBack;
        }

        /// <summary> 
        /// 註銷快捷鍵 
        /// </summary> 
        /// <param name="hWnd">持有快捷鍵窗口的句柄</param> 
        /// <param name="callBack">回調函數</param> 
        public static void UnRegist(IntPtr hWnd, HotKeyCallBackHanlder callBack)
        {
            foreach (KeyValuePair<int, HotKeyCallBackHanlder> var in keymap)
            {
                if (var.Value == callBack)
                    UnregisterHotKey(hWnd, var.Key);
            }
        }

        /// <summary> 
        /// 快捷鍵消息處理 
        /// </summary> 
        public static void ProcessHotKey(System.Windows.Forms.Message m)
        {
            if (m.Msg == WM_HOTKEY)
            {
                int id = m.WParam.ToInt32();
                HotKeyCallBackHanlder callback;
                if (keymap.TryGetValue(id, out callback))
                {
                    callback();
                }
            }
        }

        const int WM_HOTKEY = 0x312;
        static int keyid = 10;
        static Dictionary<int, HotKeyCallBackHanlder> keymap = new Dictionary<int, HotKeyCallBackHanlder>();

        public delegate void HotKeyCallBackHanlder();
    }

    enum HotkeyModifiers
    {
        MOD_ALT = 0x1,
        MOD_CONTROL = 0x2,
        MOD_SHIFT = 0x4,
        MOD_WIN = 0x8
    }

這裡通過Hotkey類實現功能的封裝,使用非常簡單。下面為參考測試代碼。

        void Test()
        {
            MessageBox.Show("Test");
        }

        protected override void WndProc(ref Message m)
        {
            base.WndProc(ref m);
            Hotkey.ProcessHotKey(m);
        }

        private void button1_Click(object sender, EventArgs e)
        {
            Hotkey.UnRegist(this.Handle, Test);
        }

到此這篇關於C#實現全局快捷鍵功能的文章就介紹到這瞭。希望對大傢的學習有所幫助,也希望大傢多多支持WalkonNet。

推薦閱讀: