HidEvent.cs
author sl
Sun, 14 Dec 2014 18:17:40 +0100
changeset 30 8ce9bdc9c5b5
parent 27 305d2ecd3b1a
child 31 958ed29f977c
permissions -rw-r--r--
Renaming some of our usage tables.
     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 
    10 
    11 namespace Hid
    12 {
    13     /// <summary>
    14     /// Represent a HID event.
    15     /// </summary>
    16     class HidEvent
    17     {
    18         public bool IsValid { get; private set; }
    19         public bool IsForeground { get; private set; }
    20         public bool IsBackground { get{return !IsForeground;} }
    21         public bool IsMouse { get; private set; }
    22         public bool IsKeyboard { get; private set; }
    23         public bool IsGeneric { get; private set; }
    24         public bool IsButtonDown { get { return Usages.Count == 1 && Usages[0] != 0; } }
    25         public bool IsButtonUp { get { return Usages.Count == 1 && Usages[0] == 0; } }
    26 
    27         public HidDevice Device { get; private set; }
    28 
    29         public ushort UsagePage { get; private set; }
    30         public ushort UsageCollection { get; private set; }
    31         public List<ushort> Usages { get; private set; }
    32 
    33 
    34         /// <summary>
    35         /// Initialize an HidEvent from a WM_INPUT message
    36         /// </summary>
    37         /// <param name="hRawInputDevice">Device Handle as provided by RAWINPUTHEADER.hDevice, typically accessed as rawinput.header.hDevice</param>
    38         public HidEvent(Message aMessage)
    39         {
    40             IsValid = false;
    41             IsKeyboard = false;
    42             IsGeneric = false;
    43 
    44             Usages = new List<ushort>();
    45 
    46             if (aMessage.Msg != Const.WM_INPUT)
    47             {
    48                 //Has to be a WM_INPUT message
    49                 return;
    50             }
    51 
    52             if (Macro.GET_RAWINPUT_CODE_WPARAM(aMessage.WParam) == Const.RIM_INPUT)
    53             {
    54                 IsForeground = true;
    55             }
    56             else if (Macro.GET_RAWINPUT_CODE_WPARAM(aMessage.WParam) == Const.RIM_INPUTSINK)
    57             {
    58                 IsForeground = false;
    59             }
    60 
    61             //Declare some pointers
    62             IntPtr rawInputBuffer = IntPtr.Zero;
    63             //My understanding is that this is basically our HID descriptor 
    64             IntPtr preParsedData = IntPtr.Zero;
    65 
    66             try
    67             {
    68                 //Fetch raw input
    69                 RAWINPUT rawInput = new RAWINPUT();
    70                 if (!RawInput.GetRawInputData(aMessage.LParam, ref rawInput, ref rawInputBuffer))
    71                 {
    72                     return;
    73                 }
    74 
    75                 //Fetch device info
    76                 RID_DEVICE_INFO deviceInfo = new RID_DEVICE_INFO();
    77                 if (!RawInput.GetDeviceInfo(rawInput.header.hDevice, ref deviceInfo))
    78                 {
    79                     return;
    80                 }
    81 
    82                 //Get various information about this HID device
    83                 Device = new Hid.HidDevice(rawInput.header.hDevice);                
    84 
    85                 if (rawInput.header.dwType == Const.RIM_TYPEHID)  //Check that our raw input is HID                        
    86                 {
    87                     IsGeneric = true;
    88 
    89                     Debug.WriteLine("WM_INPUT source device is HID.");
    90                     //Get Usage Page and Usage
    91                     //Debug.WriteLine("Usage Page: 0x" + deviceInfo.hid.usUsagePage.ToString("X4") + " Usage ID: 0x" + deviceInfo.hid.usUsage.ToString("X4"));
    92                     UsagePage = deviceInfo.hid.usUsagePage;
    93                     UsageCollection = deviceInfo.hid.usUsage;
    94 
    95                     preParsedData = RawInput.GetPreParsedData(rawInput.header.hDevice);
    96 
    97                     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
    98                         && rawInput.hid.dwCount > 0))    //Check that we have at least one HID msg
    99                     {
   100                         return;
   101                     }
   102 
   103                     //Allocate a buffer for one HID input
   104                     byte[] hidInputReport = new byte[rawInput.hid.dwSizeHid];
   105 
   106                     Debug.WriteLine("Raw input contains " + rawInput.hid.dwCount + " HID input report(s)");
   107 
   108                     //For each HID input report in our raw input
   109                     for (int i = 0; i < rawInput.hid.dwCount; i++)
   110                     {
   111                         //Compute the address from which to copy our HID input
   112                         int hidInputOffset = 0;
   113                         unsafe
   114                         {
   115                             byte* source = (byte*)rawInputBuffer;
   116                             source += sizeof(RAWINPUTHEADER) + sizeof(RAWHID) + (rawInput.hid.dwSizeHid * i);
   117                             hidInputOffset = (int)source;
   118                         }
   119 
   120                         //Copy HID input into our buffer
   121                         Marshal.Copy(new IntPtr(hidInputOffset), hidInputReport, 0, (int)rawInput.hid.dwSizeHid);
   122 
   123                         //Print HID input report in our debug output
   124                         string hidDump = "HID input report: ";
   125                         foreach (byte b in hidInputReport)
   126                         {
   127                             hidDump += b.ToString("X2");
   128                         }
   129                         Debug.WriteLine(hidDump);
   130 
   131                         //Proper parsing now
   132                         uint usageCount = 1; //Assuming a single usage per input report. Is that correct?
   133                         Win32.USAGE_AND_PAGE[] usages = new Win32.USAGE_AND_PAGE[usageCount];
   134                         Win32.HidStatus status = Win32.Function.HidP_GetUsagesEx(Win32.HIDP_REPORT_TYPE.HidP_Input, 0, usages, ref usageCount, preParsedData, hidInputReport, (uint)hidInputReport.Length);
   135                         if (status != Win32.HidStatus.HIDP_STATUS_SUCCESS)
   136                         {
   137                             Debug.WriteLine("Could not parse HID data!");
   138                         }
   139                         else
   140                         {
   141                             //Debug.WriteLine("UsagePage: 0x" + usages[0].UsagePage.ToString("X4"));
   142                             //Debug.WriteLine("Usage: 0x" + usages[0].Usage.ToString("X4"));
   143                             //Add this usage to our list
   144                             Usages.Add(usages[0].Usage);
   145                         }
   146                     }
   147 
   148                 }
   149                 else if (rawInput.header.dwType == Const.RIM_TYPEMOUSE)
   150                 {
   151                     IsMouse = true;
   152 
   153                     Debug.WriteLine("WM_INPUT source device is Mouse.");                    
   154                     // do mouse handling...
   155                 }
   156                 else if (rawInput.header.dwType == Const.RIM_TYPEKEYBOARD)
   157                 {
   158                     IsKeyboard = true;
   159 
   160                     Debug.WriteLine("WM_INPUT source device is Keyboard.");
   161                     // do keyboard handling...
   162                     Debug.WriteLine("Type: " + deviceInfo.keyboard.dwType.ToString());
   163                     Debug.WriteLine("SubType: " + deviceInfo.keyboard.dwSubType.ToString());
   164                     Debug.WriteLine("Mode: " + deviceInfo.keyboard.dwKeyboardMode.ToString());
   165                     Debug.WriteLine("Number of function keys: " + deviceInfo.keyboard.dwNumberOfFunctionKeys.ToString());
   166                     Debug.WriteLine("Number of indicators: " + deviceInfo.keyboard.dwNumberOfIndicators.ToString());
   167                     Debug.WriteLine("Number of keys total: " + deviceInfo.keyboard.dwNumberOfKeysTotal.ToString());
   168                 }
   169             }
   170             finally
   171             {
   172                 //Always executed when leaving our try block
   173                 Marshal.FreeHGlobal(rawInputBuffer);
   174                 Marshal.FreeHGlobal(preParsedData);
   175             }
   176 
   177             IsValid = true;
   178         }
   179 
   180         /// <summary>
   181         /// Print information about this device to our debug output.
   182         /// </summary>
   183         public void DebugWrite()
   184         {
   185             if (!IsValid)
   186             {
   187                 Debug.WriteLine("==== Invalid HidEvent");
   188                 return;
   189             }
   190             Device.DebugWrite();
   191             if (IsGeneric) Debug.WriteLine("==== Generic");
   192             if (IsKeyboard) Debug.WriteLine("==== Keyboard");
   193             if (IsMouse) Debug.WriteLine("==== Mouse");
   194             Debug.WriteLine("==== Foreground: " + IsForeground.ToString());
   195             Debug.WriteLine("==== UsagePage: 0x" + UsagePage.ToString("X4"));
   196             Debug.WriteLine("==== UsageCollection: 0x" + UsageCollection.ToString("X4"));
   197             foreach (ushort usage in Usages)
   198             {
   199                 Debug.WriteLine("==== Usage: 0x" + usage.ToString("X4"));
   200             }
   201         }
   202 
   203 
   204 
   205 
   206     }
   207 
   208 }