Device Info moves where it belongs into our device class.
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 == 0; } }
27 public bool IsRepeat { get { return RepeatCount != 0; } }
28 public uint RepeatCount { get; private set; }
30 public HidDevice Device { get; private set; }
32 public ushort UsagePage { get; private set; }
33 public ushort UsageCollection { get; private set; }
34 public uint UsageId { get { return ((uint)UsagePage << 16 | (uint)UsageCollection); } }
35 public List<ushort> Usages { get; private set; }
36 public byte[] InputReport { get; private set; }
38 public delegate void HidEventRepeatDelegate(HidEvent aHidEvent);
39 public event HidEventRepeatDelegate OnHidEventRepeat;
41 private System.Timers.Timer Timer { get; set; }
42 public DateTime Time { get; private set; }
43 public DateTime OriginalTime { get; private set; }
45 //Compute repeat delay and speed based on system settings
46 //Those computations were taken from the Petzold here: ftp://ftp.charlespetzold.com/ProgWinForms/4%20Custom%20Controls/NumericScan/NumericScan/ClickmaticButton.cs
47 private int iRepeatDelay = 250 * (1 + SystemInformation.KeyboardDelay);
48 private int iRepeatSpeed = 405 - 12 * SystemInformation.KeyboardSpeed;
51 /// Tells whether this event has already been disposed of.
53 public bool IsStray { get { return Timer == null; } }
56 /// We typically dispose of events as soon as we get the corresponding key up signal.
60 Timer.Enabled = false;
62 //Mark this event as a stray
67 /// Initialize an HidEvent from a WM_INPUT message
69 /// <param name="hRawInputDevice">Device Handle as provided by RAWINPUTHEADER.hDevice, typically accessed as rawinput.header.hDevice</param>
70 public HidEvent(Message aMessage, HidEventRepeatDelegate aRepeatDelegate)
79 OriginalTime = DateTime.Now;
80 Timer = new System.Timers.Timer();
81 Timer.Elapsed += (sender, e) => OnRepeatTimerElapsed(sender, e, this);
82 Usages = new List<ushort>();
83 OnHidEventRepeat += aRepeatDelegate;
85 if (aMessage.Msg != Const.WM_INPUT)
87 //Has to be a WM_INPUT message
91 if (Macro.GET_RAWINPUT_CODE_WPARAM(aMessage.WParam) == Const.RIM_INPUT)
95 else if (Macro.GET_RAWINPUT_CODE_WPARAM(aMessage.WParam) == Const.RIM_INPUTSINK)
100 //Declare some pointers
101 IntPtr rawInputBuffer = IntPtr.Zero;
106 RAWINPUT rawInput = new RAWINPUT();
107 if (!Win32.Utils.RawInput.GetRawInputData(aMessage.LParam, ref rawInput, ref rawInputBuffer))
113 //Get various information about this HID device
114 Device = new Hid.HidDevice(rawInput.header.hDevice);
116 if (rawInput.header.dwType == Const.RIM_TYPEHID) //Check that our raw input is HID
120 Debug.WriteLine("WM_INPUT source device is HID.");
121 //Get Usage Page and Usage
122 //Debug.WriteLine("Usage Page: 0x" + deviceInfo.hid.usUsagePage.ToString("X4") + " Usage ID: 0x" + deviceInfo.hid.usUsage.ToString("X4"));
123 UsagePage = Device.Info.hid.usUsagePage;
124 UsageCollection = Device.Info.hid.usUsage;
126 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
127 && rawInput.hid.dwCount > 0)) //Check that we have at least one HID msg
132 //Allocate a buffer for one HID input
133 InputReport = new byte[rawInput.hid.dwSizeHid];
135 Debug.WriteLine("Raw input contains " + rawInput.hid.dwCount + " HID input report(s)");
137 //For each HID input report in our raw input
138 for (int i = 0; i < rawInput.hid.dwCount; i++)
140 //Compute the address from which to copy our HID input
141 int hidInputOffset = 0;
144 byte* source = (byte*)rawInputBuffer;
145 source += sizeof(RAWINPUTHEADER) + sizeof(RAWHID) + (rawInput.hid.dwSizeHid * i);
146 hidInputOffset = (int)source;
149 //Copy HID input into our buffer
150 Marshal.Copy(new IntPtr(hidInputOffset), InputReport, 0, (int)rawInput.hid.dwSizeHid);
152 //Print HID input report in our debug output
153 //string hidDump = "HID input report: " + InputReportString();
154 //Debug.WriteLine(hidDump);
156 //Do proper parsing of our HID report
157 //First query our usage count
159 Win32.USAGE_AND_PAGE[] usages = null;
160 Win32.HidStatus status = Win32.Function.HidP_GetUsagesEx(Win32.HIDP_REPORT_TYPE.HidP_Input, 0, usages, ref usageCount, Device.PreParsedData, InputReport, (uint)InputReport.Length);
161 if (status == Win32.HidStatus.HIDP_STATUS_BUFFER_TOO_SMALL)
163 //Allocate a large enough buffer
164 usages = new Win32.USAGE_AND_PAGE[usageCount];
165 //...and fetch our usages
166 status = Win32.Function.HidP_GetUsagesEx(Win32.HIDP_REPORT_TYPE.HidP_Input, 0, usages, ref usageCount, Device.PreParsedData, InputReport, (uint)InputReport.Length);
167 if (status != Win32.HidStatus.HIDP_STATUS_SUCCESS)
169 Debug.WriteLine("Second pass could not parse HID data: " + status.ToString());
172 else if (status != Win32.HidStatus.HIDP_STATUS_SUCCESS)
174 Debug.WriteLine("First pass could not parse HID data: " + status.ToString());
177 Debug.WriteLine("Usage count: " + usageCount.ToString());
179 //Copy usages into this event
182 foreach (USAGE_AND_PAGE up in usages)
184 //Debug.WriteLine("UsagePage: 0x" + usages[0].UsagePage.ToString("X4"));
185 //Debug.WriteLine("Usage: 0x" + usages[0].Usage.ToString("X4"));
186 //Add this usage to our list
187 Usages.Add(up.Usage);
192 else if (rawInput.header.dwType == Const.RIM_TYPEMOUSE)
196 Debug.WriteLine("WM_INPUT source device is Mouse.");
197 // do mouse handling...
199 else if (rawInput.header.dwType == Const.RIM_TYPEKEYBOARD)
203 Debug.WriteLine("WM_INPUT source device is Keyboard.");
204 // do keyboard handling...
205 Debug.WriteLine("Type: " + Device.Info.keyboard.dwType.ToString());
206 Debug.WriteLine("SubType: " + Device.Info.keyboard.dwSubType.ToString());
207 Debug.WriteLine("Mode: " + Device.Info.keyboard.dwKeyboardMode.ToString());
208 Debug.WriteLine("Number of function keys: " + Device.Info.keyboard.dwNumberOfFunctionKeys.ToString());
209 Debug.WriteLine("Number of indicators: " + Device.Info.keyboard.dwNumberOfIndicators.ToString());
210 Debug.WriteLine("Number of keys total: " + Device.Info.keyboard.dwNumberOfKeysTotal.ToString());
215 //Always executed when leaving our try block
216 Marshal.FreeHGlobal(rawInputBuffer);
222 //TODO: Make this optional
223 StartRepeatTimer(iRepeatDelay);
229 public void StartRepeatTimer(double aInterval)
235 Timer.Enabled = false;
236 //Initial delay do not use auto reset
237 //After our initial delay however we do setup our timer one more time using auto reset
238 Timer.AutoReset = (RepeatCount!=0);
239 Timer.Interval = aInterval;
240 Timer.Enabled = true;
243 static private void OnRepeatTimerElapsed(object sender, ElapsedEventArgs e, HidEvent aHidEvent)
245 if (aHidEvent.IsStray)
247 //Skip events if canceled
251 aHidEvent.RepeatCount++;
252 aHidEvent.Time = DateTime.Now;
253 if (aHidEvent.RepeatCount==1)
255 //Re-Start our timer only after the initial delay
256 aHidEvent.StartRepeatTimer(aHidEvent.iRepeatSpeed);
259 //Broadcast our repeat event
260 aHidEvent.OnHidEventRepeat(aHidEvent);
264 /// Print information about this device to our debug output.
266 public void DebugWrite()
270 Debug.WriteLine("==== Invalid HidEvent");
274 if (IsGeneric) Debug.WriteLine("==== Generic");
275 if (IsKeyboard) Debug.WriteLine("==== Keyboard");
276 if (IsMouse) Debug.WriteLine("==== Mouse");
277 Debug.WriteLine("==== Foreground: " + IsForeground.ToString());
278 Debug.WriteLine("==== UsagePage: 0x" + UsagePage.ToString("X4"));
279 Debug.WriteLine("==== UsageCollection: 0x" + UsageCollection.ToString("X4"));
280 Debug.WriteLine("==== InputReport: 0x" + InputReportString());
281 foreach (ushort usage in Usages)
283 Debug.WriteLine("==== Usage: 0x" + usage.ToString("X4"));
290 /// <returns></returns>
291 public string InputReportString()
294 foreach (byte b in InputReport)
296 hidDump += b.ToString("X2");
303 /// Create a list view item describing this HidEvent
305 /// <returns></returns>
306 public ListViewItem ToListViewItem()
308 string usageText = "";
310 foreach (ushort usage in Usages)
318 UsagePage usagePage = (UsagePage)UsagePage;
321 case Hid.UsagePage.Consumer:
322 usageText += ((Hid.UsageTables.ConsumerControl)usage).ToString();
325 case Hid.UsagePage.WindowsMediaCenterRemoteControl:
326 usageText += ((Hid.UsageTables.WindowsMediaCenterRemoteControl)usage).ToString();
330 usageText += usage.ToString("X2");
335 ListViewItem item = new ListViewItem(new[] { usageText, InputReportString(), UsagePage.ToString("X2"), UsageCollection.ToString("X2"), RepeatCount.ToString(), Time.ToString("HH:mm:ss:fff") });