Fixing stray event issues.
2 using System.Windows.Forms;
3 using System.Runtime.InteropServices;
4 using System.Diagnostics;
6 using Microsoft.Win32.SafeHandles;
8 using System.Collections.Generic;
15 /// Represent a HID event.
17 public class HidEvent: IDisposable
19 public bool IsValid { get; private set; }
20 public bool IsForeground { get; private set; }
21 public bool IsBackground { get{return !IsForeground;} }
22 public bool IsMouse { get; private set; }
23 public bool IsKeyboard { get; private set; }
24 public bool IsGeneric { get; private set; }
25 public bool IsButtonDown { get { return Usages.Count == 1 && Usages[0] != 0; } }
26 public bool IsButtonUp { get { return Usages.Count == 1 && Usages[0] == 0; } }
27 public bool IsRepeat { get; private set; }
29 public HidDevice Device { get; private set; }
31 public ushort UsagePage { get; private set; }
32 public ushort UsageCollection { get; private set; }
33 public uint UsageId { get { return ((uint)UsagePage << 16 | (uint)UsageCollection); } }
34 public List<ushort> Usages { get; private set; }
35 public delegate void HidEventRepeatDelegate(HidEvent aHidEvent);
36 public event HidEventRepeatDelegate OnHidEventRepeat;
38 private System.Timers.Timer Timer { get; set; }
41 /// Tells whether this event has already been disposed of.
43 public bool IsStray { get { return Timer == null; } }
49 Timer.Enabled = false;
55 /// Initialize an HidEvent from a WM_INPUT message
57 /// <param name="hRawInputDevice">Device Handle as provided by RAWINPUTHEADER.hDevice, typically accessed as rawinput.header.hDevice</param>
58 public HidEvent(Message aMessage, HidEventRepeatDelegate aRepeatDelegate)
65 Timer = new System.Timers.Timer();
66 Usages = new List<ushort>();
67 OnHidEventRepeat += aRepeatDelegate;
69 if (aMessage.Msg != Const.WM_INPUT)
71 //Has to be a WM_INPUT message
75 if (Macro.GET_RAWINPUT_CODE_WPARAM(aMessage.WParam) == Const.RIM_INPUT)
79 else if (Macro.GET_RAWINPUT_CODE_WPARAM(aMessage.WParam) == Const.RIM_INPUTSINK)
84 //Declare some pointers
85 IntPtr rawInputBuffer = IntPtr.Zero;
86 //My understanding is that this is basically our HID descriptor
87 IntPtr preParsedData = IntPtr.Zero;
92 RAWINPUT rawInput = new RAWINPUT();
93 if (!RawInput.GetRawInputData(aMessage.LParam, ref rawInput, ref rawInputBuffer))
99 RID_DEVICE_INFO deviceInfo = new RID_DEVICE_INFO();
100 if (!RawInput.GetDeviceInfo(rawInput.header.hDevice, ref deviceInfo))
105 //Get various information about this HID device
106 Device = new Hid.HidDevice(rawInput.header.hDevice);
108 if (rawInput.header.dwType == Const.RIM_TYPEHID) //Check that our raw input is HID
112 Debug.WriteLine("WM_INPUT source device is HID.");
113 //Get Usage Page and Usage
114 //Debug.WriteLine("Usage Page: 0x" + deviceInfo.hid.usUsagePage.ToString("X4") + " Usage ID: 0x" + deviceInfo.hid.usUsage.ToString("X4"));
115 UsagePage = deviceInfo.hid.usUsagePage;
116 UsageCollection = deviceInfo.hid.usUsage;
118 preParsedData = RawInput.GetPreParsedData(rawInput.header.hDevice);
120 if (!(rawInput.hid.dwSizeHid > 1 //Make sure our HID msg size more than 1. In fact the first ushort is irrelevant to us for now
121 && rawInput.hid.dwCount > 0)) //Check that we have at least one HID msg
126 //Allocate a buffer for one HID input
127 byte[] hidInputReport = new byte[rawInput.hid.dwSizeHid];
129 Debug.WriteLine("Raw input contains " + rawInput.hid.dwCount + " HID input report(s)");
131 //For each HID input report in our raw input
132 for (int i = 0; i < rawInput.hid.dwCount; i++)
134 //Compute the address from which to copy our HID input
135 int hidInputOffset = 0;
138 byte* source = (byte*)rawInputBuffer;
139 source += sizeof(RAWINPUTHEADER) + sizeof(RAWHID) + (rawInput.hid.dwSizeHid * i);
140 hidInputOffset = (int)source;
143 //Copy HID input into our buffer
144 Marshal.Copy(new IntPtr(hidInputOffset), hidInputReport, 0, (int)rawInput.hid.dwSizeHid);
146 //Print HID input report in our debug output
147 string hidDump = "HID input report: ";
148 foreach (byte b in hidInputReport)
150 hidDump += b.ToString("X2");
152 Debug.WriteLine(hidDump);
155 uint usageCount = 1; //Assuming a single usage per input report. Is that correct?
156 Win32.USAGE_AND_PAGE[] usages = new Win32.USAGE_AND_PAGE[usageCount];
157 Win32.HidStatus status = Win32.Function.HidP_GetUsagesEx(Win32.HIDP_REPORT_TYPE.HidP_Input, 0, usages, ref usageCount, preParsedData, hidInputReport, (uint)hidInputReport.Length);
158 if (status != Win32.HidStatus.HIDP_STATUS_SUCCESS)
160 Debug.WriteLine("Could not parse HID data!");
164 //Debug.WriteLine("UsagePage: 0x" + usages[0].UsagePage.ToString("X4"));
165 //Debug.WriteLine("Usage: 0x" + usages[0].Usage.ToString("X4"));
166 //Add this usage to our list
167 Usages.Add(usages[0].Usage);
172 else if (rawInput.header.dwType == Const.RIM_TYPEMOUSE)
176 Debug.WriteLine("WM_INPUT source device is Mouse.");
177 // do mouse handling...
179 else if (rawInput.header.dwType == Const.RIM_TYPEKEYBOARD)
183 Debug.WriteLine("WM_INPUT source device is Keyboard.");
184 // do keyboard handling...
185 Debug.WriteLine("Type: " + deviceInfo.keyboard.dwType.ToString());
186 Debug.WriteLine("SubType: " + deviceInfo.keyboard.dwSubType.ToString());
187 Debug.WriteLine("Mode: " + deviceInfo.keyboard.dwKeyboardMode.ToString());
188 Debug.WriteLine("Number of function keys: " + deviceInfo.keyboard.dwNumberOfFunctionKeys.ToString());
189 Debug.WriteLine("Number of indicators: " + deviceInfo.keyboard.dwNumberOfIndicators.ToString());
190 Debug.WriteLine("Number of keys total: " + deviceInfo.keyboard.dwNumberOfKeysTotal.ToString());
195 //Always executed when leaving our try block
196 Marshal.FreeHGlobal(rawInputBuffer);
197 Marshal.FreeHGlobal(preParsedData);
202 StartRepeatTimer(SystemInformation.KeyboardDelay*250+250);
209 /// Print information about this device to our debug output.
211 public void DebugWrite()
215 Debug.WriteLine("==== Invalid HidEvent");
219 if (IsGeneric) Debug.WriteLine("==== Generic");
220 if (IsKeyboard) Debug.WriteLine("==== Keyboard");
221 if (IsMouse) Debug.WriteLine("==== Mouse");
222 Debug.WriteLine("==== Foreground: " + IsForeground.ToString());
223 Debug.WriteLine("==== UsagePage: 0x" + UsagePage.ToString("X4"));
224 Debug.WriteLine("==== UsageCollection: 0x" + UsageCollection.ToString("X4"));
225 foreach (ushort usage in Usages)
227 Debug.WriteLine("==== Usage: 0x" + usage.ToString("X4"));
231 public void StartRepeatTimer(double aInterval)
237 Timer.Enabled = false;
238 Timer.AutoReset = false;
239 Timer.Interval = aInterval;
240 Timer.Elapsed += (sender, e) => OnRepeatTimerElapsed(sender, e, this);
241 Timer.Enabled = true;
244 private void OnRepeatTimerElapsed(object sender, ElapsedEventArgs e, HidEvent aHidEvent)
246 if (aHidEvent.IsStray)
248 //Skip events if canceled
251 aHidEvent.IsRepeat = true;
252 StartRepeatTimer(1000/(SystemInformation.KeyboardSpeed+2.5));
253 OnHidEventRepeat(aHidEvent);
256 public ListViewItem ToListViewItem()
258 //TODO: What to do with multiple usage
260 UsagePage usagePage = (UsagePage)UsagePage;
263 case Hid.UsagePage.Consumer:
264 usage = ((Hid.UsageTables.ConsumerControl)Usages[0]).ToString();
267 case Hid.UsagePage.WindowsMediaCenterRemoteControl:
268 usage = ((Hid.UsageTables.WindowsMediaCenterRemoteControl)Usages[0]).ToString();
273 ListViewItem item = new ListViewItem(new[] { usage, UsagePage.ToString("X2"), UsageCollection.ToString("X2"), IsRepeat.ToString() });