1: using System;
2: using System.Runtime.InteropServices;
3: using System.Windows.Forms;
4:
5: namespace TestRegisterHotKey
6: {
7: public class WindowsShell
8: {
9: public enum ModifierEnum
10: {
11: MOD_ALT = 0x1,
12: MOD_CONTROL = 0x2,
13: MOD_SHIFT = 0x4,
14: MOD_WIN = 0x8
15: }
16:
17: private static int keyId;
18: public static int WM_HOTKEY = 0x312;
19:
20: [DllImport("user32.dll")]
21: private static extern bool RegisterHotKey(
22: IntPtr hWnd, int id, int fsModifiers, int vlc);
23:
24: [DllImport("user32.dll")]
25: private static extern bool UnregisterHotKey(
26: IntPtr hWnd, int id);
27:
28: public static void RegisterHotKey(Form f, Keys key)
29: {
30: int modifiers = 0;
31: if ((key & Keys.Alt) == Keys.Alt)
32: modifiers = modifiers | (int)WindowsShell.ModifierEnum.MOD_ALT;
33: if ((key & Keys.Control) == Keys.Control)
34: modifiers = modifiers | (int)WindowsShell.ModifierEnum.MOD_CONTROL;
35: if ((key & Keys.Shift) == Keys.Shift)
36: modifiers = modifiers | (int)WindowsShell.ModifierEnum.MOD_SHIFT;
37: Keys k = key & ~Keys.Control & ~Keys.Shift & ~Keys.Alt;
38: f.Invoke(new Action(() =>
39: {
40: keyId = f.GetHashCode();
41: RegisterHotKey((IntPtr)f.Handle, keyId, modifiers, (int)k);
42: }));
43: }
44:
45: public static void UnregisterHotKey(Form f)
46: {
47: try
48: {
49: f.Invoke(new Action(() =>
50: {
51: UnregisterHotKey(f.Handle, keyId);
52: }));
53: }
54: catch (Exception)
55: {
56: throw;
57: }
58: }
59:
60: }
61: }