Consistent naming fixes in our usage tables enumerations.
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.
16 /// TODO: Rename this into HidRawInput?
18 public class HidEvent : IDisposable
20 public bool IsValid { get; private set; }
21 public bool IsForeground { get; private set; }
22 public bool IsBackground { get { return !IsForeground; } }
23 public bool IsMouse { get; private set; }
24 public bool IsKeyboard { get; private set; }
25 public bool IsGeneric { get; private set; }
26 public bool IsButtonDown { get { return Usages.Count == 1 && Usages[0] != 0; } }
27 public bool IsButtonUp { get { return Usages.Count == 0; } }
28 public bool IsRepeat { get { return RepeatCount != 0; } }
29 public uint RepeatCount { get; private set; }
31 public HidDevice Device { get; private set; }
33 public ushort UsagePage { get; private set; }
34 public ushort UsageCollection { get; private set; }
35 public uint UsageId { get { return ((uint)UsagePage << 16 | (uint)UsageCollection); } }
36 public List<ushort> Usages { get; private set; }
37 //TODO: We need a collection of input report
38 public byte[] InputReport { get; private set; }
40 public delegate void HidEventRepeatDelegate(HidEvent aHidEvent);
41 public event HidEventRepeatDelegate OnHidEventRepeat;
43 private System.Timers.Timer Timer { get; set; }
44 public DateTime Time { get; private set; }
45 public DateTime OriginalTime { get; private set; }
47 //Compute repeat delay and speed based on system settings
48 //Those computations were taken from the Petzold here: ftp://ftp.charlespetzold.com/ProgWinForms/4%20Custom%20Controls/NumericScan/NumericScan/ClickmaticButton.cs
49 private int iRepeatDelay = 250 * (1 + SystemInformation.KeyboardDelay);
50 private int iRepeatSpeed = 405 - 12 * SystemInformation.KeyboardSpeed;
53 /// Tells whether this event has already been disposed of.
55 public bool IsStray { get { return Timer == null; } }
58 /// We typically dispose of events as soon as we get the corresponding key up signal.
62 Timer.Enabled = false;
64 //Mark this event as a stray
69 /// Initialize an HidEvent from a WM_INPUT message
71 /// <param name="hRawInputDevice">Device Handle as provided by RAWINPUTHEADER.hDevice, typically accessed as rawinput.header.hDevice</param>
72 public HidEvent(Message aMessage, HidEventRepeatDelegate aRepeatDelegate)
81 OriginalTime = DateTime.Now;
82 Timer = new System.Timers.Timer();
83 Timer.Elapsed += (sender, e) => OnRepeatTimerElapsed(sender, e, this);
84 Usages = new List<ushort>();
85 OnHidEventRepeat += aRepeatDelegate;
87 if (aMessage.Msg != Const.WM_INPUT)
89 //Has to be a WM_INPUT message
93 if (Macro.GET_RAWINPUT_CODE_WPARAM(aMessage.WParam) == Const.RIM_INPUT)
97 else if (Macro.GET_RAWINPUT_CODE_WPARAM(aMessage.WParam) == Const.RIM_INPUTSINK)
102 //Declare some pointers
103 IntPtr rawInputBuffer = IntPtr.Zero;
108 RAWINPUT rawInput = new RAWINPUT();
109 if (!Win32.RawInput.GetRawInputData(aMessage.LParam, ref rawInput, ref rawInputBuffer))
115 //Get various information about this HID device
116 Device = new Hid.HidDevice(rawInput.header.hDevice);
118 if (rawInput.header.dwType == Win32.RawInputDeviceType.RIM_TYPEHID) //Check that our raw input is HID
122 Debug.WriteLine("WM_INPUT source device is HID.");
123 //Get Usage Page and Usage
124 //Debug.WriteLine("Usage Page: 0x" + deviceInfo.hid.usUsagePage.ToString("X4") + " Usage ID: 0x" + deviceInfo.hid.usUsage.ToString("X4"));
125 UsagePage = Device.Info.hid.usUsagePage;
126 UsageCollection = Device.Info.hid.usUsage;
128 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
129 && rawInput.hid.dwCount > 0)) //Check that we have at least one HID msg
134 //Allocate a buffer for one HID input
135 InputReport = new byte[rawInput.hid.dwSizeHid];
137 Debug.WriteLine("Raw input contains " + rawInput.hid.dwCount + " HID input report(s)");
139 //For each HID input report in our raw input
140 for (int i = 0; i < rawInput.hid.dwCount; i++)
142 //Compute the address from which to copy our HID input
143 int hidInputOffset = 0;
146 byte* source = (byte*)rawInputBuffer;
147 source += sizeof(RAWINPUTHEADER) + sizeof(RAWHID) + (rawInput.hid.dwSizeHid * i);
148 hidInputOffset = (int)source;
151 //Copy HID input into our buffer
152 Marshal.Copy(new IntPtr(hidInputOffset), InputReport, 0, (int)rawInput.hid.dwSizeHid);
154 //Print HID input report in our debug output
155 //string hidDump = "HID input report: " + InputReportString();
156 //Debug.WriteLine(hidDump);
158 //Do proper parsing of our HID report
159 //First query our usage count
161 Win32.USAGE_AND_PAGE[] usages = null;
162 Win32.HidStatus status = Win32.Function.HidP_GetUsagesEx(Win32.HIDP_REPORT_TYPE.HidP_Input, 0, usages, ref usageCount, Device.PreParsedData, InputReport, (uint)InputReport.Length);
163 if (status == Win32.HidStatus.HIDP_STATUS_BUFFER_TOO_SMALL)
165 //Allocate a large enough buffer
166 usages = new Win32.USAGE_AND_PAGE[usageCount];
167 //...and fetch our usages
168 status = Win32.Function.HidP_GetUsagesEx(Win32.HIDP_REPORT_TYPE.HidP_Input, 0, usages, ref usageCount, Device.PreParsedData, InputReport, (uint)InputReport.Length);
169 if (status != Win32.HidStatus.HIDP_STATUS_SUCCESS)
171 Debug.WriteLine("Second pass could not parse HID data: " + status.ToString());
174 else if (status != Win32.HidStatus.HIDP_STATUS_SUCCESS)
176 Debug.WriteLine("First pass could not parse HID data: " + status.ToString());
179 Debug.WriteLine("Usage count: " + usageCount.ToString());
181 //Copy usages into this event
184 foreach (USAGE_AND_PAGE up in usages)
186 //Debug.WriteLine("UsagePage: 0x" + usages[0].UsagePage.ToString("X4"));
187 //Debug.WriteLine("Usage: 0x" + usages[0].Usage.ToString("X4"));
188 //Add this usage to our list
189 Usages.Add(up.Usage);
194 else if (rawInput.header.dwType == RawInputDeviceType.RIM_TYPEMOUSE)
198 Debug.WriteLine("WM_INPUT source device is Mouse.");
199 // do mouse handling...
201 else if (rawInput.header.dwType == RawInputDeviceType.RIM_TYPEKEYBOARD)
205 Debug.WriteLine("WM_INPUT source device is Keyboard.");
206 // do keyboard handling...
207 Debug.WriteLine("Type: " + Device.Info.keyboard.dwType.ToString());
208 Debug.WriteLine("SubType: " + Device.Info.keyboard.dwSubType.ToString());
209 Debug.WriteLine("Mode: " + Device.Info.keyboard.dwKeyboardMode.ToString());
210 Debug.WriteLine("Number of function keys: " + Device.Info.keyboard.dwNumberOfFunctionKeys.ToString());
211 Debug.WriteLine("Number of indicators: " + Device.Info.keyboard.dwNumberOfIndicators.ToString());
212 Debug.WriteLine("Number of keys total: " + Device.Info.keyboard.dwNumberOfKeysTotal.ToString());
217 //Always executed when leaving our try block
218 Marshal.FreeHGlobal(rawInputBuffer);
224 //TODO: Make this optional
225 //StartRepeatTimer(iRepeatDelay);
231 public void StartRepeatTimer(double aInterval)
237 Timer.Enabled = false;
238 //Initial delay do not use auto reset
239 //After our initial delay however we do setup our timer one more time using auto reset
240 Timer.AutoReset = (RepeatCount != 0);
241 Timer.Interval = aInterval;
242 Timer.Enabled = true;
245 static private void OnRepeatTimerElapsed(object sender, ElapsedEventArgs e, HidEvent aHidEvent)
247 if (aHidEvent.IsStray)
249 //Skip events if canceled
253 aHidEvent.RepeatCount++;
254 aHidEvent.Time = DateTime.Now;
255 if (aHidEvent.RepeatCount == 1)
257 //Re-Start our timer only after the initial delay
258 aHidEvent.StartRepeatTimer(aHidEvent.iRepeatSpeed);
261 //Broadcast our repeat event
262 aHidEvent.OnHidEventRepeat(aHidEvent);
266 /// Print information about this device to our debug output.
268 public void DebugWrite()
272 Debug.WriteLine("==== Invalid HidEvent");
276 if (IsGeneric) Debug.WriteLine("==== Generic");
277 if (IsKeyboard) Debug.WriteLine("==== Keyboard");
278 if (IsMouse) Debug.WriteLine("==== Mouse");
279 Debug.WriteLine("==== Foreground: " + IsForeground.ToString());
280 Debug.WriteLine("==== UsagePage: 0x" + UsagePage.ToString("X4"));
281 Debug.WriteLine("==== UsageCollection: 0x" + UsageCollection.ToString("X4"));
282 Debug.WriteLine("==== InputReport: 0x" + InputReportString());
283 foreach (ushort usage in Usages)
285 Debug.WriteLine("==== Usage: 0x" + usage.ToString("X4"));
292 /// <returns></returns>
293 public string InputReportString()
296 foreach (byte b in InputReport)
298 hidDump += b.ToString("X2");
305 /// Create a list view item describing this HidEvent
307 /// <returns></returns>
308 public ListViewItem ToListViewItem()
310 string usageText = "";
312 foreach (ushort usage in Usages)
320 UsagePage usagePage = (UsagePage)UsagePage;
323 case Hid.UsagePage.Consumer:
324 usageText += ((Hid.Usage.ConsumerControl)usage).ToString();
327 case Hid.UsagePage.WindowsMediaCenterRemoteControl:
328 usageText += ((Hid.Usage.WindowsMediaCenterRemoteControl)usage).ToString();
332 usageText += usage.ToString("X2");
337 ListViewItem item = new ListViewItem(new[] { usageText, InputReportString(), UsagePage.ToString("X2"), UsageCollection.ToString("X2"), RepeatCount.ToString(), Time.ToString("HH:mm:ss:fff") });