private void ProcessKeyPress(RawInputKeyPressEventArgs args) { Console.WriteLine($"{args.Device.Name} {args.Device.ID} {args.CorrectedKey} {args.KeyPressState}"); if (args.Device.Handle == IntPtr.Zero) { EnqueueDecision(args.VKey, args.KeyPressState, false, IntPtr.Zero); return; } Delegate[] handlers; if (!Enabled) { handlers = HookDisabledOnKeyPress?.GetInvocationList(); if (handlers != null) { foreach (RawInputKeyPressEvent handler in handlers) { handler.Invoke(this, args); if (args.Handled) { break; } } } EnqueueDecision(args.VKey, args.KeyPressState, args.Handled, args.Device.Handle); return; } handlers = OnKeyPress?.GetInvocationList(); if (handlers != null) { foreach (RawInputKeyPressEvent handler in handlers) { handler.Invoke(this, args); if (args.Handled) { break; } } } EnqueueDecision(args.VKey, args.KeyPressState, args.Handled, args.Device.Handle); if (args.Handled && (handlers = HandledKeyPress?.GetInvocationList()) != null) { args.Handled = false; new Thread(() => { foreach (RawInputKeyPressEvent handler in handlers) { handler.Invoke(this, args); if (args.Handled) { break; } } }) { IsBackground = true, Name = "HandledKeyPress thread" }.Start(); } }
private void ProcessRawInput(IntPtr hDevice) { if (DevicesByHandle.Count == 0) { return; } int dwSize = 0; Win32.GetRawInputData(hDevice, DataCommand.RID_INPUT, IntPtr.Zero, ref dwSize, Marshal.SizeOf(typeof(RawInputHeader))); if (dwSize != Win32.GetRawInputData(hDevice, DataCommand.RID_INPUT, out InputData rawBuffer, ref dwSize, Marshal.SizeOf(typeof(RawInputHeader)))) { Console.WriteLine("Error getting the rawinput buffer"); return; } int virtualKey = rawBuffer.data.keyboard.VKey; int makeCode = rawBuffer.data.keyboard.Makecode; int flags = rawBuffer.data.keyboard.Flags; if (virtualKey == Win32.KEYBOARD_OVERRUN_MAKE_CODE) { return; } Device device; lock (lockObj) { if (!DevicesByHandle.ContainsKey(rawBuffer.header.hDevice)) { Console.WriteLine($"Handle: {rawBuffer.header.hDevice} was not in the device list."); return; } device = DevicesByHandle[rawBuffer.header.hDevice]; } bool isE0BitSet = (flags & Win32.RI_KEY_E0) != 0; bool isBreakBitSet = (flags & Win32.RI_KEY_BREAK) != 0; RawInputKeyPressEventArgs args = new RawInputKeyPressEventArgs(this, device, virtualKey, VirtualKeyCorrection(rawBuffer.header.hDevice, virtualKey, isE0BitSet, makeCode), isBreakBitSet ? KeyState.Break : KeyState.Make); args.LastKeyPressState = device.Pressed.Contains(args.CorrectedKey) ? KeyState.Make : KeyState.Break; List <Keys> pressed = device.Pressed.ToList(); if (args.KeyPressState == KeyState.Make && !pressed.Contains(args.CorrectedKey)) { pressed.Add(args.CorrectedKey); } else if (args.KeyPressState == KeyState.Break && pressed.Contains(args.CorrectedKey)) { pressed.RemoveAll(k => k == args.CorrectedKey); } device.LastPressed = device.Pressed; device.Pressed = pressed.ToArray(); ProcessKeyPress(args); }