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);
        }

 

 

 

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