HidEvent.cs
author sl
Wed, 24 Dec 2014 11:17:45 +0100
changeset 42 219e9a418456
parent 41 dd603eba46ca
child 43 5c7f34c627b9
permissions -rw-r--r--
Fixing stray event issues.
     1 using System;
     2 using System.Windows.Forms;
     3 using System.Runtime.InteropServices;
     4 using System.Diagnostics;
     5 using System.Text;
     6 using Microsoft.Win32.SafeHandles;
     7 using Win32;
     8 using System.Collections.Generic;
     9 using System.Timers;
    10 
    11 
    12 namespace Hid
    13 {
    14     /// <summary>
    15     /// Represent a HID event.
    16     /// </summary>
    17     public class HidEvent: IDisposable
    18     {
    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; }
    28 
    29         public HidDevice Device { get; private set; }
    30 
    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;
    37 
    38         private System.Timers.Timer Timer { get; set; }
    39 
    40         /// <summary>
    41         /// Tells whether this event has already been disposed of.
    42         /// </summary>
    43         public bool IsStray { get { return Timer == null; } }
    44 
    45 
    46 
    47         public void Dispose()
    48         {
    49             Timer.Enabled = false;
    50             Timer.Dispose();
    51             Timer = null;
    52         }
    53 
    54         /// <summary>
    55         /// Initialize an HidEvent from a WM_INPUT message
    56         /// </summary>
    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)
    59         {
    60             IsRepeat = false;
    61             IsValid = false;
    62             IsKeyboard = false;
    63             IsGeneric = false;
    64 
    65             Timer = new System.Timers.Timer();
    66             Usages = new List<ushort>();
    67             OnHidEventRepeat += aRepeatDelegate;
    68 
    69             if (aMessage.Msg != Const.WM_INPUT)
    70             {
    71                 //Has to be a WM_INPUT message
    72                 return;
    73             }
    74 
    75             if (Macro.GET_RAWINPUT_CODE_WPARAM(aMessage.WParam) == Const.RIM_INPUT)
    76             {
    77                 IsForeground = true;
    78             }
    79             else if (Macro.GET_RAWINPUT_CODE_WPARAM(aMessage.WParam) == Const.RIM_INPUTSINK)
    80             {
    81                 IsForeground = false;
    82             }
    83 
    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;
    88 
    89             try
    90             {
    91                 //Fetch raw input
    92                 RAWINPUT rawInput = new RAWINPUT();
    93                 if (!RawInput.GetRawInputData(aMessage.LParam, ref rawInput, ref rawInputBuffer))
    94                 {
    95                     return;
    96                 }
    97 
    98                 //Fetch device info
    99                 RID_DEVICE_INFO deviceInfo = new RID_DEVICE_INFO();
   100                 if (!RawInput.GetDeviceInfo(rawInput.header.hDevice, ref deviceInfo))
   101                 {
   102                     return;
   103                 }
   104 
   105                 //Get various information about this HID device
   106                 Device = new Hid.HidDevice(rawInput.header.hDevice);                
   107 
   108                 if (rawInput.header.dwType == Const.RIM_TYPEHID)  //Check that our raw input is HID                        
   109                 {
   110                     IsGeneric = true;
   111 
   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;
   117 
   118                     preParsedData = RawInput.GetPreParsedData(rawInput.header.hDevice);
   119 
   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
   122                     {
   123                         return;
   124                     }
   125 
   126                     //Allocate a buffer for one HID input
   127                     byte[] hidInputReport = new byte[rawInput.hid.dwSizeHid];
   128 
   129                     Debug.WriteLine("Raw input contains " + rawInput.hid.dwCount + " HID input report(s)");
   130 
   131                     //For each HID input report in our raw input
   132                     for (int i = 0; i < rawInput.hid.dwCount; i++)
   133                     {
   134                         //Compute the address from which to copy our HID input
   135                         int hidInputOffset = 0;
   136                         unsafe
   137                         {
   138                             byte* source = (byte*)rawInputBuffer;
   139                             source += sizeof(RAWINPUTHEADER) + sizeof(RAWHID) + (rawInput.hid.dwSizeHid * i);
   140                             hidInputOffset = (int)source;
   141                         }
   142 
   143                         //Copy HID input into our buffer
   144                         Marshal.Copy(new IntPtr(hidInputOffset), hidInputReport, 0, (int)rawInput.hid.dwSizeHid);
   145 
   146                         //Print HID input report in our debug output
   147                         string hidDump = "HID input report: ";
   148                         foreach (byte b in hidInputReport)
   149                         {
   150                             hidDump += b.ToString("X2");
   151                         }
   152                         Debug.WriteLine(hidDump);
   153 
   154                         //Proper parsing now
   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)
   159                         {
   160                             Debug.WriteLine("Could not parse HID data!");
   161                         }
   162                         else
   163                         {
   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);
   168                         }
   169                     }
   170 
   171                 }
   172                 else if (rawInput.header.dwType == Const.RIM_TYPEMOUSE)
   173                 {
   174                     IsMouse = true;
   175 
   176                     Debug.WriteLine("WM_INPUT source device is Mouse.");                    
   177                     // do mouse handling...
   178                 }
   179                 else if (rawInput.header.dwType == Const.RIM_TYPEKEYBOARD)
   180                 {
   181                     IsKeyboard = true;
   182 
   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());
   191                 }
   192             }
   193             finally
   194             {
   195                 //Always executed when leaving our try block
   196                 Marshal.FreeHGlobal(rawInputBuffer);
   197                 Marshal.FreeHGlobal(preParsedData);
   198             }
   199 
   200             if (Usages[0]!=0)
   201             {
   202                 StartRepeatTimer(SystemInformation.KeyboardDelay*250+250);
   203             }
   204             
   205             IsValid = true;
   206         }
   207 
   208         /// <summary>
   209         /// Print information about this device to our debug output.
   210         /// </summary>
   211         public void DebugWrite()
   212         {
   213             if (!IsValid)
   214             {
   215                 Debug.WriteLine("==== Invalid HidEvent");
   216                 return;
   217             }
   218             Device.DebugWrite();
   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)
   226             {
   227                 Debug.WriteLine("==== Usage: 0x" + usage.ToString("X4"));
   228             }
   229         }
   230 
   231         public void StartRepeatTimer(double aInterval)
   232         {
   233             if (Timer == null)
   234             {
   235                 return;
   236             }
   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;
   242         }
   243 
   244         private void OnRepeatTimerElapsed(object sender, ElapsedEventArgs e, HidEvent aHidEvent)
   245         {
   246             if (aHidEvent.IsStray)
   247             {
   248                 //Skip events if canceled
   249                 return;
   250             }
   251             aHidEvent.IsRepeat = true;
   252             StartRepeatTimer(1000/(SystemInformation.KeyboardSpeed+2.5));            
   253             OnHidEventRepeat(aHidEvent);
   254         }
   255 
   256         public ListViewItem ToListViewItem()
   257         {
   258             //TODO: What to do with multiple usage
   259             string usage = "";
   260             UsagePage usagePage = (UsagePage)UsagePage;
   261             switch (usagePage)
   262             {
   263                 case Hid.UsagePage.Consumer:
   264                     usage = ((Hid.UsageTables.ConsumerControl)Usages[0]).ToString();
   265                     break;
   266 
   267                 case Hid.UsagePage.WindowsMediaCenterRemoteControl:
   268                     usage = ((Hid.UsageTables.WindowsMediaCenterRemoteControl)Usages[0]).ToString();
   269                     break;
   270 
   271             }
   272 
   273             ListViewItem item = new ListViewItem(new[] { usage, UsagePage.ToString("X2"), UsageCollection.ToString("X2"), IsRepeat.ToString() });
   274             return item;
   275         }
   276 
   277     }
   278 
   279 }