C# 快捷鍵/hotkey簡單例子

1.導入dll

        [System.Runtime.InteropServices.DllImport("user32.dll")] //申明API函數
        public static extern bool RegisterHotKey(
         IntPtr hWnd, // handle to window
         int id, // hot key identifier
         uint fsModifiers, // key-modifier options
         Keys vk // virtual-key code
        );
        [System.Runtime.InteropServices.DllImport("user32.dll")] //申明API函數
        public static extern bool UnregisterHotKey(
         IntPtr hWnd, // handle to window
         int id // hot key identifier
        );

2.定義hotkey

RegisterHotKey(Handle, 100, 0, Keys.Home); //註冊熱鍵爲home


//關閉程序前,需要卸載熱鍵
UnregisterHotKey(Handle, 100);//卸載快捷鍵

 

3.重載WndProc函數

 protected override void WndProc(ref Message m) // 重載WndProc函數
        {
            const int WM_HOTKEY = 0x0312; //判斷hotkey標誌

            try
            {
                if (m.Msg != WM_HOTKEY || m.WParam.ToInt32() != 100)
                {
                    goto EndFunction;
                }

                //獲取當前窗口信息
                IntPtr hWnd = GetForegroundWindow();
                uint procId = 0;
                GetWindowThreadProcessId(hWnd, out procId);
                var proc = Process.GetProcessById((int)procId);
                string titleName = proc.MainWindowTitle;     

                int fileLen = titleName.LastIndexOf('-');
                string fileFullPath = titleName.Substring(0,fileLen).Trim();
                this.textBoxFileNme.Text = fileFullPath;

                //執行函數......

            
            }
            catch (Exception ex)
            {
                this.textBoxLog.AppendText("Error!!!"+ex.Message);
            }
            EndFunction:
            base.WndProc(ref m);
        }

 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章