Archiwista [cz. 7 – Skrót klawiszowy]
Jedną z kluczowych funkcjonalności aplikacji jest tworzenie kopii zapasowych plików źródłowych. Za każdym razem, gdy użytkownik przyciśnie skrót klawiszowy program ma rozpocząć proces archiwizacji. W tym wpisie przedstawię etapy tworzenia klas, które pozwolą na nasłuchiwanie klawiatury oraz interpretację skrótów.
Nasłuchiwanie
Pierwszą rzeczą potrzebną do rozpoznania skrótu klawiszowego jest jego otrzymanie, więc pierwszą czynnością, jaką zrobiłem było przeszukanie Internetu na temat różnych możliwości nasłuchiwania klawiatury komputera. Jak się okazało istnieje wiele możliwości, jednak każda niosła ze sobą jakieś korzyści i limitacje. Jednak jedna pojawiała się w prawie każdym wpisie, jaki odwiedziłem. Global keyboard hooks pozwalają na słuchanie informacji z kolejki systemu operacyjnego dzięki czemu istnieje możliwość nasłuchiwania wszystkich klawiszy.
W ramach tej aplikacji wybrałem wersję low level keyboard hook poszukując informacji jak używać tego mechanizmu natknąłem się na wpis zawierający gotową klasę umożliwiającą podłączenie się oraz nasłuchiwanie klawiszy. Dlatego użyję tej klasy niestety nie posiada ona wszystkich funkcjonalności, jakich potrzebuję dlatego dokonam modyfikacji. Bez żadnych modyfikacji klasa informuje użytkownika tylko o tym, który klawisz został naciśnięty, ale nie o tym, czy klawisz został puszczony. Aby wykryć skróty klawiszowe będę potrzebował informacji o tym, czy klawisze typu: Alt, Ctrl, Shift są wciśnięte, w tym celu zmodyfikowałem kod dodając dwa eventy OnKeyDown oraz OnKeyUp. Mając informacje, czy dany klawisz jest wciśnięty czy puszczony mogę przystąpić do pisania klasy zarządzającej całością.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 |
/* * Source: * http://www.dylansweb.com/2014/10/low-level-global-keyboard-hook-sink-in-c-net/ * * Modified by: http://kkolodziejczak.net/ */ public class LowLevelKeyboardListener { private const int WH_KEYBOARD_LL = 13; private const int WM_KEYDOWN = 0x0100; private const int WM_KEYUP = 0x0101; private const int WM_SYSKEYDOWN = 0x0104; private const int WM_SYSKEYUP = 0x0105; [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)] private static extern IntPtr SetWindowsHookEx(int idHook, LowLevelKeyboardProc lpfn, IntPtr hMod, uint dwThreadId); [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] private static extern bool UnhookWindowsHookEx(IntPtr hhk); [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)] private static extern IntPtr CallNextHookEx(IntPtr hhk, int nCode, IntPtr wParam, IntPtr lParam); [DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)] private static extern IntPtr GetModuleHandle(string lpModuleName); public delegate IntPtr LowLevelKeyboardProc(int nCode, IntPtr wParam, IntPtr lParam); public event EventHandler public event EventHandler private LowLevelKeyboardProc _proc; private IntPtr _hookID = IntPtr.Zero; public LowLevelKeyboardListener() { _proc = HookCallback; } public void HookKeyboard() { _hookID = SetHook(_proc); } public void UnHookKeyboard() { UnhookWindowsHookEx(_hookID); } private IntPtr SetHook(LowLevelKeyboardProc proc) { using (Process curProcess = Process.GetCurrentProcess()) using (ProcessModule curModule = curProcess.MainModule) { return SetWindowsHookEx(WH_KEYBOARD_LL, proc, GetModuleHandle(curModule.ModuleName), 0); } } private IntPtr HookCallback(int nCode, IntPtr wParam, IntPtr lParam) { if (nCode >= 0 && wParam == (IntPtr)WM_KEYDOWN || wParam == (IntPtr)WM_SYSKEYDOWN) { int vkCode = Marshal.ReadInt32(lParam); if (OnKeyDown != null) { OnKeyDown(this, new KeyPressedArgs(KeyInterop.KeyFromVirtualKey(vkCode))); } } if (nCode >= 0 && wParam == (IntPtr)WM_KEYUP || wParam == (IntPtr)WM_SYSKEYUP) { int vkCode = Marshal.ReadInt32(lParam); if (OnKeyUp != null) { OnKeyUp(this, new KeyPressedArgs(KeyInterop.KeyFromVirtualKey(vkCode))); } } return CallNextHookEx(_hookID, nCode, wParam, lParam); } } public class KeyPressedArgs : EventArgs { public Key KeyPressed { get; private set; } public KeyPressedArgs(Key key) { KeyPressed = key; } } |
Skrót klawiszowy
Jeszcze przed przystąpieniem do tworzenia klasy, która będzie zarządzała całością muszę zaprojektować obiekt przedstawiający skrót klawiszowy. Klasa ta będzie miała informacje o tym, jakie klawisze muszą zostać wciśnięte jednocześnie, aby skrót był uznany za prawidłowy oraz event OnShortcutActivated, który zostanie uruchomiony w przypadku wykrycia odpowiedniej kombinacji klawiszy.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 |
/// /// Class that represents keyboard shortcut /// public class KeyboardShortcut { #region Public Properties /// /// Shotcut Key /// public Key Key { get; set; } /// /// Indicates if Alt key is pressed /// public bool Alt { get; set; } /// /// Indicates if Ctrl key is pressed /// public bool Ctrl { get; set; } /// /// Indicates if Shift key is pressed /// public bool Shift { get; set; } #endregion #region Event /// /// Event that is fired when shortcut criteria are meet /// public event EventHandler OnShortcutActivated; #endregion #region Constructor /// /// Default Constructor /// public KeyboardShortcut() { } /// /// Copy Constructor /// public KeyboardShortcut(KeyboardShortcut source) { this.Key = source.Key; this.Alt = source.Alt; this.Ctrl = source.Ctrl; this.Shift = source.Shift; this.OnShortcutActivated = source.OnShortcutActivated; } #endregion #region Public Methods /// /// Fires shortcut methods that are connected to /// public void Execute() { if (OnShortcutActivated != null) { OnShortcutActivated(this, new EventArgs()); } } #endregion #region Override public override string ToString() { StringBuilder sb = new StringBuilder(); if (Ctrl) sb.Append("Ctrl + "); if (Alt) sb.Append("Alt + "); if (Shift) sb.Append("Shift + "); return $"{sb.ToString()}{Key.ToString()}"; } #endregion } |
Zarządzanie skrótami
Aby nie tworzyć dużej ilości połączeń i nasłuchiwać każdy klawisz w każdym obiekcie reprezentującym skrót stworzę klasę zarządzającą skrótami. KeyboardShortcutManager posiada listę skrótów, gdy tylko zostanie jakikolwiek skrót z listy wciśnięty uruchomi się odpowiedni event. Dodatkowo w celu łatwej obsługi manager posiada interfejs składający się jak na razie z trzech metod RegisterKeyboardShortcut, UnRegisterKeyboardShortcut. Metody odpowiednio pozwalają na dodanie oraz usunięcie skrótu z listy nasłuchiwanych skrótów klawiszowych. Oraz metodę RecordKeyboardShortcut, która nagrywa następny skrót klawiszowy i zostanie on podmieniony dla skrótu podanego jako argument. Niestety podczas projektowania tej metody wystąpiło kilka problemów logicznych przez sposób, w jaki otrzymuję informację nie jestem w stanie zwrócić utworzonego skrótu. Aktualne rozwiązanie bazuje na fladze, która jest ustawiana dzięki temu manager wie, że kolejnym razem, kiedy użytkownik puści klawisz ma zapisać skrót klawiszowy jako nowy.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 |
/// /// Class that manages shortcuts. /// Manager is listening to keyboard strokes /// when registered key combination appear will execute shortcuts action. /// public class KeyboardShortcutManager { #region Private Fields /// /// Listener that allows to perform sertent action on Key Presses. /// private LowLevelKeyboardListener _KeyboardListener; /// /// Singleton /// private static KeyboardShortcutManager _Instance; /// /// Indicate if /// private bool _IsRecording; /// /// Shortcut type that will be replaced after recording /// private KeyboardShortcut _ShortcutToRecord; /// /// ShortcutSelected by user /// public List #endregion #region Public Properties /// /// Indicates if Alt key is holded (Left and Right are the same) /// public bool IsAltPressed { get; private set; } /// /// Indicates if Ctrl key is holded (Left and Right are the same) /// public bool IsCtrlPressed { get; private set; } /// /// Indicates if Shift key is holded (Left and Right are the same) /// public bool IsShiftPressed { get; private set; } /// /// Key that is holded /// public Key KeyPressed { get; private set; } /// /// ShortcutManager Singleton instance /// public static KeyboardShortcutManager Instance { get { if (_Instance == null) _Instance = new KeyboardShortcutManager(); return _Instance; } private set { _Instance = value; } } #endregion #region Constructor /// /// Default constructor /// private KeyboardShortcutManager() { // Prepare Keyboard listener _KeyboardListener = new LowLevelKeyboardListener(); _KeyboardListener.OnKeyUp += OnKeyUp; _KeyboardListener.OnKeyDown += OnKeyDown; // Start to listen _KeyboardListener.HookKeyboard(); } #endregion #region Destructor /// /// Default destructor /// ~KeyboardShortcutManager() { // Cleanup _KeyboardListener.OnKeyUp -= OnKeyUp; _KeyboardListener.OnKeyDown -= OnKeyDown; _KeyboardListener.UnHookKeyboard(); } #endregion #region Private Methods /// /// OnKeyDown Event Method /// /// /// private void OnKeyDown(object sender, KeyPressedArgs e) { SwitchKey(e.KeyPressed, true); if (_IsRecording == true) return; foreach (var shortcut in _RegisteredShortcuts) { if (IsShortcutPressed(shortcut)) { shortcut.Execute(); } } } /// /// Checks if shortcut is pressed /// /// /// private bool IsShortcutPressed(KeyboardShortcut shortcut) { return (IsAltPressed == shortcut.Alt && IsCtrlPressed == shortcut.Ctrl && IsShiftPressed == shortcut.Shift && KeyPressed == shortcut.Key); } /// /// OnKeyUp Event Method /// /// /// private void OnKeyUp(object sender, KeyPressedArgs e) { SwitchKey(e.KeyPressed, false); } /// /// Changes value of keys /// /// /// private void SwitchKey(Key key, bool value) { switch (key) { case Key.LeftCtrl: case Key.RightCtrl: IsCtrlPressed = value; break; case Key.LeftAlt: case Key.RightAlt: IsAltPressed = value; break; case Key.LeftShift: case Key.RightShift: IsShiftPressed = value; break; default: if(value == false) { if (_IsRecording == true) { //TODO: Save Selected Shortcut in user Settings UnRegisterKeyboardShortcut(_ShortcutToRecord); var NewShortcut = new KeyboardShortcut(_ShortcutToRecord) { Key = key, Alt = IsAltPressed, Ctrl = IsCtrlPressed, Shift = IsShiftPressed, }; _RegisteredShortcuts.Add(NewShortcut); _IsRecording = false; } KeyPressed = Key.None; } else { KeyPressed = key; } break; } } #endregion #region Public Methods /// /// Sets flag that indicates shortcut recording, the next combination of keys pressed by the user will be set as a shortcut /// /// Shortcut with setted public void RecordKeyboardShortcut(KeyboardShortcut shortcut) { _ShortcutToRecord = shortcut; _IsRecording = true; } /// /// Register shortcut to listen to. /// /// public void RegisterKeyboardShortcut(KeyboardShortcut shortcut) { if (_RegisteredShortcuts == null) _RegisteredShortcuts = new List _RegisteredShortcuts.Add(shortcut); } /// /// Removes shortcut from shortcut list /// /// public void UnRegisterKeyboardShortcut(KeyboardShortcut shortcut) { if (_RegisteredShortcuts == null) return; if (_RegisteredShortcuts.Contains(shortcut)) { _RegisteredShortcuts.Remove(shortcut); } } #endregion } |
Kończąc
Podczas tworzenia klasy reprezentującej skrót klawiszowy przeładowałem również metodę ToString, aby mieć możliwość bezpośredniego Bindowania obiektu KeyboardShortcut do zawartości przycisku. Niestety zawartość przycisku pozostawała pusta. Okazało się, że wyłączenie stylu przycisku dało efekt, jaki oczekiwałem od samego początku. Wewnątrz zawartości przycisku wyświetliła się wartość zwrócona z przeładowanej metody ToString. Rozwiązaniem okazało się stworzenie ValueConvertera, którego jedynym zadaniem jest wywołanie metody ToString. Następne dodałem ToStringValueConverter do stylu bazowego przycisku i przycisk działa tak jak powinien.
Rozwiązanie przedstawione podczas nagrywania nowego skrótu spełnia swoje zadanie, którym jest zmiana klawiszy skrótu, ale niestety nie pozwala na jego zwrócenie bez zawiłych mechanizmów. Nie jestem usatysfakcjonowany takim rozwiązaniem w tym tygodniu zabrakło czasu na jego dopracowanie. Dlatego w następnym tygodniu będę pracował nad jego ulepszeniem.
Cały kod aplikacji można zobaczyć na moim koncie github /kkolodziejczak/Archivist