HidHandler.cs
author StephaneLenclud
Sat, 14 Feb 2015 23:41:12 +0100
changeset 53 e7831b781512
parent 41 dd603eba46ca
child 76 831ebeeecfdf
permissions -rw-r--r--
Device Info moves where it belongs into our device class.
     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     /// Our HID handler manages raw input registrations, processes WM_INPUT messages and broadcasts HID events in return.
    15     /// </summary>
    16     public class HidHandler
    17     {
    18         public delegate void HidEventHandler(object aSender, HidEvent aHidEvent);
    19         public event HidEventHandler OnHidEvent;
    20         List<HidEvent> iHidEvents;
    21 
    22 
    23         public bool IsRegistered { get; private set; }
    24 
    25         public HidHandler(RAWINPUTDEVICE[] aRawInputDevices)
    26         {
    27             iHidEvents=new List<HidEvent>();
    28             IsRegistered = Function.RegisterRawInputDevices(aRawInputDevices, (uint)aRawInputDevices.Length, (uint)Marshal.SizeOf(aRawInputDevices[0]));
    29         }
    30 
    31         public void ProcessInput(Message aMessage)
    32         {
    33             Hid.HidEvent hidEvent = new Hid.HidEvent(aMessage, OnHidEventRepeat);
    34             hidEvent.DebugWrite();
    35 
    36             if (!hidEvent.IsValid || !hidEvent.IsGeneric)
    37             {
    38                 Debug.WriteLine("Skipping HID message.");
    39                 return;
    40             }
    41 
    42             //
    43             if (hidEvent.IsButtonUp)
    44             {
    45                 //This is a key up event
    46                 //We need to discard any events belonging to the same page and collection
    47                 for (int i = (iHidEvents.Count-1); i >= 0; i--)
    48                 {
    49                     if (iHidEvents[i].UsageId == hidEvent.UsageId)
    50                     {
    51                         iHidEvents[i].Dispose();
    52                         iHidEvents.RemoveAt(i);
    53                     }
    54                 }
    55             }
    56             else
    57             {
    58                 //Keep that event until we get a key up message
    59                 iHidEvents.Add(hidEvent);
    60             }
    61 
    62             //Broadcast our events
    63             OnHidEvent(this, hidEvent);    
    64         }
    65 
    66         public void OnHidEventRepeat(HidEvent aHidEvent)
    67         {
    68             //Broadcast our events
    69             OnHidEvent(this, aHidEvent);    
    70         }
    71 
    72     }
    73 
    74 }