Created
January 27, 2017 01:07
-
-
Save jmelosegui/6f13e07ccaee225dad1bff53d5063c71 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Diagnostics; | |
using System.Runtime.InteropServices; | |
using System.Windows.Input; | |
using static PInvoke.User32; | |
using static PInvoke.Kernel32; | |
namespace WpfApplication1 | |
{ | |
public class KeyboardListener | |
{ | |
public event EventHandler<KeyPressedArgs> OnKeyPressed; | |
private readonly WindowsHookDelegate action; | |
private SafeHookHandle safeHandle = new SafeHookHandle(); | |
public KeyboardListener() | |
{ | |
action = HookCallback; | |
} | |
public void HookKeyboard() | |
{ | |
safeHandle = SetHook(action); | |
} | |
public void UnHookKeyboard() | |
{ | |
safeHandle.Dispose(); | |
} | |
private SafeHookHandle SetHook(WindowsHookDelegate action) | |
{ | |
using (Process curProcess = Process.GetCurrentProcess()) | |
{ | |
using (ProcessModule curModule = curProcess.MainModule) | |
{ | |
return SetWindowsHookEx(WindowsHookType.WH_KEYBOARD_LL, action, | |
GetModuleHandle(curModule.ModuleName).DangerousGetHandle(), 0); | |
} | |
} | |
} | |
private int HookCallback(int nCode, IntPtr wParam, IntPtr lParam) | |
{ | |
if (nCode >= 0 && wParam == (IntPtr)WindowMessage.WM_KEYDOWN || wParam == (IntPtr)WindowMessage.WM_SYSKEYDOWN) | |
{ | |
int virtualKey = Marshal.ReadInt32(lParam); | |
OnKeyPressed?.Invoke(this, new KeyPressedArgs(KeyInterop.KeyFromVirtualKey(virtualKey))); | |
} | |
return CallNextHookEx(safeHandle.DangerousGetHandle(), nCode, wParam, lParam); | |
} | |
} | |
public class KeyPressedArgs : EventArgs | |
{ | |
public Key KeyPressed { get; private set; } | |
public KeyPressedArgs(Key key) | |
{ | |
KeyPressed = key; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment