Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Diagnostics;
- using System.Runtime.InteropServices;
- using System.Windows.Input;
- using System.Threading.Tasks;
- using System.Windows.Forms;
- // Adapted from http://www.dylansweb.com/2014/10/low-level-global-keyboard-hook-sink-in-c-net/
- namespace Compose_Key_for_Windows
- {
- class KeyHook
- {
- private const int WH_KEYBOARD_LL = 13;
- private const int WM_KEYDOWN = 0x0100;
- private const int WM_SYSKEYDOWN = 0x0104;
- [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
- private static extern IntPtr SetWindowsHookEx(int idHook, LLKeyboardProc 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 LLKeyboardProc(int nCode, IntPtr wParam, IntPtr lParam);
- public event EventHandler<KeyPressedArgs> OnKeyPressed;
- private LLKeyboardProc _proc;
- private IntPtr _hookID = IntPtr.Zero;
- public void LLKeyboardListener()
- {
- _proc = HookCallback;
- }
- public void HookKeyboard()
- {
- _hookID = SetHook(_proc);
- }
- public void UnhookKeyboard()
- {
- UnhookWindowsHookEx(_hookID);
- }
- private IntPtr SetHook(LLKeyboardProc 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 (OnKeyPressed != null)
- {
- KeysConverter kc = new KeysConverter();
- OnKeyPressed(this, new KeyPressedArgs((Keys)Enum.Parse(typeof(Keys), kc.ConvertToString(vkCode))));
- }
- }
- return CallNextHookEx(_hookID, nCode, wParam, lParam);
- }
- }
- public class KeyPressedArgs : EventArgs
- {
- public Keys KeyPressed { get; private set; }
- public KeyPressedArgs(Keys key)
- {
- KeyPressed = key;
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement