以下文章轉載自http://www.dotblogs.com.tw/jimmyyu/archive/2009/06/03/8665.aspx
01
class HotKey
02
{
03
[DllImport("user32.dll",
SetLastError = true)]
04
public static extern bool RegisterHotKey(
05
IntPtr hWnd,
06
07
int id,
08
KeyModifiers fsModifiers,
09
10
Keys vk
11
12
);
13
14
[DllImport("user32.dll",
SetLastError = true)]
15
public static extern bool UnregisterHotKey(
16
IntPtr hWnd,
17
18
int id
19
20
);
21
22
[Flags()]
23
public enum KeyModifiers
24
{
25
None = 0,
26
Alt = 1,
27
Ctrl = 2,
28
Shift = 4,
29
WindowsKey = 8
30
}
31
}

02

03

04

05

06

07

08

09

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

然後在Form的Activated事件中註冊所要使用的HotKey,如下方範 例,我總共註冊了幾個常用的Hot-Key組合:
01
//設定hot key
02
private void Form1_Activated(object
sender, EventArgs e)
03
{
04
//HotKey.RegisterHotKey(Handle,
100, HotKey.KeyModifiers.Shift, Keys.S);
05
//Ctrl-S存檔
06
HotKey.RegisterHotKey(Handle, 101,
HotKey.KeyModifiers.Ctrl, Keys.S);
07
//Esc放棄這筆修改
08
HotKey.RegisterHotKey(Handle, 102,
HotKey.KeyModifiers.None, Keys.Escape);
09
//Ctrl-E編輯這筆
10
HotKey.RegisterHotKey(Handle, 103,
HotKey.KeyModifiers.Ctrl, Keys.E);
11
//Ctrl-A新增
12
HotKey.RegisterHotKey(Handle, 104,
HotKey.KeyModifiers.Ctrl, Keys.A);
13
//Ctrl-D刪除這筆
14
HotKey.RegisterHotKey(Handle, 105,
HotKey.KeyModifiers.Ctrl, Keys.D);
15
}

02

03

04

05

06

07

08

09

10

11

12

13

14

15

然後透過複寫WinProc來完成Hot-Key所要執行的工作:
01
protected override void
WndProc(ref Message m)
02
{
03
const int WM_HOTKEY = 0x0312;
04
switch (m.Msg)
05
{
06
case
WM_HOTKEY:
07
switch
(m.WParam.ToInt32())
08
{
09
case
101: //Ctrl+S
10
//save
11
break;
12
case
102: //Esc
13
//escape
14
break;
15
case
103: //Ctrl+E
16
//edit
17
break;
18
case
104: //Ctrl+A
19
//add
20
break;
21
case
105: //Ctrl+D
22
//delete
23
break;
24
}
25
break;
26
}
27
28
base.WndProc(ref m);
29
}

02

03

04

05

06

07

08

09

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

全站熱搜