c#为程序添加全局热键的方法

在程序失去焦点或者在后台运行时,可以通过使用全局热键的方式,进行一些快捷的操作,如QQ默认操作中ctrl+alt+A调出截图功能。

在Windows中实现热键功能需要使用win32的Api函数RegisterHotKey和UnregisterHotKey。

示例Demo(含代码)

实现代码:

一、注册热键:

 

 1     public class HotKey
 2     {
 3         //============= 1、声明注册热键的方法 ==================
 4         [DllImport("user32.dll", EntryPoint = "RegisterHotKey")]
 5         private static extern int RegisterHotKey(IntPtr hWnd, int nID, int nModifiers, int nVK);
 6 
 7         [DllImport("user32.dll", EntryPoint = "RegisterHotKey")]
 8         private static extern int RegisterHotKey(IntPtr hWnd, int nID, int nModifiers, Keys VK);
 9 
10         [DllImport("user32.dll", EntryPoint = "UnregisterHotKey")]
11         private static extern int UnregisterHotKey(IntPtr hWnd, int nID);
12 
13         //============= 2、声明组合键常量 ========================
14         public const int MOD_NONE = 0;
15         public const int MOD_ALT = 1;
16         public const int MOD_CTRL = 2;
17         public const int MOD_SHIFT = 4;
18 
19         public enum MOD
20         {
21             MOD_NONE = 0,
22             MOD_ALT = 1,
23             MOD_CTRL = 2,
24             MOD_SHIFT = 4,
25             MOD_WIN = 8
26         }
27 
28         //============= 3、实现注册热键的方法 ====================
29 
30         /// <summary>
31         /// 注册热键
32         /// </summary>
33         /// <param name="hWnd">窗口句柄</param>
34         /// <param name="nID">热键标识</param>
35         /// <param name="modKey">组合键</param>
36         /// <param name="nVK">热键</param>
37         /// <returns></returns>
38         public static bool RegHotKey(IntPtr hWnd, int nID, int modKey, int nVK)
39         {
40             //========== 3.1、先释放该窗口句柄下具有相同标识的热键 =============
41             UnregisterHotKey(hWnd, nID);
42 
43             //========== 3.2、注册热键 =========================================
44             int nResult = RegisterHotKey(hWnd, nID, modKey, nVK);
45 
46             //========== 3.3、返回注册结果 =====================================
47             return nResult != 0 ? true : false;
48         }
注册热键

 

 

二、在调用热键的窗口程序中,重写WndProc方法响应热键:

 

 

 1         private const int nHotKeyID = 0xabcd;           //热键标识
 2         /// <summary>
 3         /// 重写WndProc响应热键方法
 4         /// </summary>
 5         /// <param name="m"></param>
 6         protected override void WndProc(ref Message m)
 7         {
 8             switch (m.WParam.ToInt32())
 9             {
10                 case nHotKeyID:
11                     Method();       //热键调用的方法
12                     break;
13             }
14 
15             base.WndProc(ref m);
16         }
响应热键

 

全局热键的注册工作完成,还有一些需要注意的方面:

1、关于定义热键的标识符,引用程序必须定义一个0X0000-0xBFFF范围的值;

2、经测试,F12键无法进行注册,有可能是系统占用。(如有误,还请路过的高手指教);

附上示例Demo(含代码)

 

posted @ 2013-08-13 15:22  流水带走了青春  阅读(897)  评论(0编辑  收藏  举报