Consolidation and adding rebracer settings.
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 { 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 delegate void HidEventRepeatDelegate(HidEvent aHidEvent);
37 public event HidEventRepeatDelegate OnHidEventRepeat;
39 private System.Timers.Timer Timer { get; set; }
40 public DateTime Time { get; private set; }
41 public DateTime OriginalTime { get; private set; }
43 //Compute repeat delay and speed based on system settings
44 //Those computations were taken from the Petzold here: ftp://ftp.charlespetzold.com/ProgWinForms/4%20Custom%20Controls/NumericScan/NumericScan/ClickmaticButton.cs
45 private int iRepeatDelay = 250 * (1 + SystemInformation.KeyboardDelay);
46 private int iRepeatSpeed = 405 - 12 * SystemInformation.KeyboardSpeed;
49 /// Tells whether this event has already been disposed of.
51 public bool IsStray { get { return Timer == null; } }
54 /// We typically dispose of events as soon as we get the corresponding key up signal.
58 Timer.Enabled = false;
60 //Mark this event as a stray
65 /// Initialize an HidEvent from a WM_INPUT message
67 /// <param name="hRawInputDevice">Device Handle as provided by RAWINPUTHEADER.hDevice, typically accessed as rawinput.header.hDevice</param>
68 public HidEvent(Message aMessage, HidEventRepeatDelegate aRepeatDelegate)
77 OriginalTime = DateTime.Now;
78 Timer = new System.Timers.Timer();
79 Timer.Elapsed += (sender, e) => OnRepeatTimerElapsed(sender, e, this);
80 Usages = new List<ushort>();
81 OnHidEventRepeat += aRepeatDelegate;
83 if (aMessage.Msg != Const.WM_INPUT)
85 //Has to be a WM_INPUT message
89 if (Macro.GET_RAWINPUT_CODE_WPARAM(aMessage.WParam) == Const.RIM_INPUT)
93 else if (Macro.GET_RAWINPUT_CODE_WPARAM(aMessage.WParam) == Const.RIM_INPUTSINK)
98 //Declare some pointers
99 IntPtr rawInputBuffer = IntPtr.Zero;
100 //My understanding is that this is basically our HID descriptor
101 IntPtr preParsedData = IntPtr.Zero;
106 RAWINPUT rawInput = new RAWINPUT();
107 if (!Win32.Utils.RawInput.GetRawInputData(aMessage.LParam, ref rawInput, ref rawInputBuffer))
113 RID_DEVICE_INFO deviceInfo = new RID_DEVICE_INFO();
114 if (!Win32.Utils.RawInput.GetDeviceInfo(rawInput.header.hDevice, ref deviceInfo))
119 //Get various information about this HID device
120 Device = new Hid.HidDevice(rawInput.header.hDevice);
122 if (rawInput.header.dwType == Const.RIM_TYPEHID) //Check that our raw input is HID
126 Debug.WriteLine("WM_INPUT source device is HID.");
127 //Get Usage Page and Usage
128 //Debug.WriteLine("Usage Page: 0x" + deviceInfo.hid.usUsagePage.ToString("X4") + " Usage ID: 0x" + deviceInfo.hid.usUsage.ToString("X4"));
129 UsagePage = deviceInfo.hid.usUsagePage;
130 UsageCollection = deviceInfo.hid.usUsage;
132 preParsedData = Win32.Utils.RawInput.GetPreParsedData(rawInput.header.hDevice);
134 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
135 && rawInput.hid.dwCount > 0)) //Check that we have at least one HID msg
140 //Allocate a buffer for one HID input
141 byte[] hidInputReport = new byte[rawInput.hid.dwSizeHid];
143 Debug.WriteLine("Raw input contains " + rawInput.hid.dwCount + " HID input report(s)");
145 //For each HID input report in our raw input
146 for (int i = 0; i < rawInput.hid.dwCount; i++)
148 //Compute the address from which to copy our HID input
149 int hidInputOffset = 0;
152 byte* source = (byte*)rawInputBuffer;
153 source += sizeof(RAWINPUTHEADER) + sizeof(RAWHID) + (rawInput.hid.dwSizeHid * i);
154 hidInputOffset = (int)source;
157 //Copy HID input into our buffer
158 Marshal.Copy(new IntPtr(hidInputOffset), hidInputReport, 0, (int)rawInput.hid.dwSizeHid);
160 //Print HID input report in our debug output
161 string hidDump = "HID input report: ";
162 foreach (byte b in hidInputReport)
164 hidDump += b.ToString("X2");
166 Debug.WriteLine(hidDump);
169 uint usageCount = 1; //Assuming a single usage per input report. Is that correct?
170 Win32.USAGE_AND_PAGE[] usages = new Win32.USAGE_AND_PAGE[usageCount];
171 Win32.HidStatus status = Win32.Function.HidP_GetUsagesEx(Win32.HIDP_REPORT_TYPE.HidP_Input, 0, usages, ref usageCount, preParsedData, hidInputReport, (uint)hidInputReport.Length);
172 if (status != Win32.HidStatus.HIDP_STATUS_SUCCESS)
174 Debug.WriteLine("Could not parse HID data!");
178 //Debug.WriteLine("UsagePage: 0x" + usages[0].UsagePage.ToString("X4"));
179 //Debug.WriteLine("Usage: 0x" + usages[0].Usage.ToString("X4"));
180 //Add this usage to our list
181 Usages.Add(usages[0].Usage);
186 else if (rawInput.header.dwType == Const.RIM_TYPEMOUSE)
190 Debug.WriteLine("WM_INPUT source device is Mouse.");
191 // do mouse handling...
193 else if (rawInput.header.dwType == Const.RIM_TYPEKEYBOARD)
197 Debug.WriteLine("WM_INPUT source device is Keyboard.");
198 // do keyboard handling...
199 Debug.WriteLine("Type: " + deviceInfo.keyboard.dwType.ToString());
200 Debug.WriteLine("SubType: " + deviceInfo.keyboard.dwSubType.ToString());
201 Debug.WriteLine("Mode: " + deviceInfo.keyboard.dwKeyboardMode.ToString());
202 Debug.WriteLine("Number of function keys: " + deviceInfo.keyboard.dwNumberOfFunctionKeys.ToString());
203 Debug.WriteLine("Number of indicators: " + deviceInfo.keyboard.dwNumberOfIndicators.ToString());
204 Debug.WriteLine("Number of keys total: " + deviceInfo.keyboard.dwNumberOfKeysTotal.ToString());
209 //Always executed when leaving our try block
210 Marshal.FreeHGlobal(rawInputBuffer);
211 Marshal.FreeHGlobal(preParsedData);
217 StartRepeatTimer(iRepeatDelay);
224 /// Print information about this device to our debug output.
226 public void DebugWrite()
230 Debug.WriteLine("==== Invalid HidEvent");
234 if (IsGeneric) Debug.WriteLine("==== Generic");
235 if (IsKeyboard) Debug.WriteLine("==== Keyboard");
236 if (IsMouse) Debug.WriteLine("==== Mouse");
237 Debug.WriteLine("==== Foreground: " + IsForeground.ToString());
238 Debug.WriteLine("==== UsagePage: 0x" + UsagePage.ToString("X4"));
239 Debug.WriteLine("==== UsageCollection: 0x" + UsageCollection.ToString("X4"));
240 foreach (ushort usage in Usages)
242 Debug.WriteLine("==== Usage: 0x" + usage.ToString("X4"));
246 public void StartRepeatTimer(double aInterval)
252 Timer.Enabled = false;
253 //Initial delay do not use auto reset
254 //After our initial delay however we do setup our timer one more time using auto reset
255 Timer.AutoReset = (RepeatCount!=0);
256 Timer.Interval = aInterval;
257 Timer.Enabled = true;
260 static private void OnRepeatTimerElapsed(object sender, ElapsedEventArgs e, HidEvent aHidEvent)
262 if (aHidEvent.IsStray)
264 //Skip events if canceled
268 aHidEvent.RepeatCount++;
269 aHidEvent.Time = DateTime.Now;
270 if (aHidEvent.RepeatCount==1)
272 //Re-Start our timer only after the initial delay
273 aHidEvent.StartRepeatTimer(aHidEvent.iRepeatSpeed);
276 //Broadcast our repeat event
277 aHidEvent.OnHidEventRepeat(aHidEvent);
280 public ListViewItem ToListViewItem()
282 //TODO: What to do with multiple usage
284 UsagePage usagePage = (UsagePage)UsagePage;
287 case Hid.UsagePage.Consumer:
288 usage = ((Hid.UsageTables.ConsumerControl)Usages[0]).ToString();
291 case Hid.UsagePage.WindowsMediaCenterRemoteControl:
292 usage = ((Hid.UsageTables.WindowsMediaCenterRemoteControl)Usages[0]).ToString();
297 ListViewItem item = new ListViewItem(new[] { usage, UsagePage.ToString("X2"), UsageCollection.ToString("X2"), RepeatCount.ToString(), Time.ToString("HH:mm:ss:fff") });