Exemple #1
0
        /// <summary>
        ///     Returns a list of raw input device handles and raw input device types.
        /// </summary>
        /// <returns>The list of raw input device handles and raw input device types.</returns>
        public static List <Tuple <HANDLE, RIM_TYPE> > EnumerateDevices()
        {
            var size = (uint)Marshal.SizeOf(typeof(RAWINPUTDEVICELIST));

            uint deviceCount = 0;

            var err = GetRawInputDeviceList(null, ref deviceCount, size);

            if (err == uint.MaxValue)
            {
                throw new Exception(string.Format("Error enumerating raw input devices. (Error code: 0x{0:X8})", WinKernel.GetLastError()));
            }

            if (deviceCount == 0)
            {
                return(new List <Tuple <LRESULT, RIM_TYPE> >());
            }

            var tmp = new RAWINPUTDEVICELIST[deviceCount + 16]; // Just a few more, for the case they just got attached.

            err = GetRawInputDeviceList(tmp, ref deviceCount, size);
            if (err == uint.MaxValue)
            {
                throw new Exception(string.Format("Error enumerating raw input devices. (Error code: 0x{0:X8})", WinKernel.GetLastError()));
            }

            var ret = new List <Tuple <LRESULT, RIM_TYPE> >();

            for (var i = 0; i < deviceCount; i++)
            {
                ret.Add(new Tuple <LRESULT, RIM_TYPE>(tmp[i].hDevice, tmp[i].dwType));
            }

            return(ret);
        }
Exemple #2
0
        public static IEnumerable <(RID_DEVICE_INFO deviceInfo, IntPtr deviceHandle)> GetDeviceList()
        {
            uint numDevices = 0;
            int  cbSize     = Marshal.SizeOf(typeof(RAWINPUTDEVICELIST));

            if (WinApi.GetRawInputDeviceList(IntPtr.Zero, ref numDevices, (uint)cbSize) == 0)            //Return value isn't zero if there is an error
            {
                IntPtr pRawInputDeviceList = Marshal.AllocHGlobal((int)(cbSize * numDevices));
                WinApi.GetRawInputDeviceList(pRawInputDeviceList, ref numDevices, (uint)cbSize);

                for (int i = 0; i < numDevices; i++)
                {
                    RAWINPUTDEVICELIST rid = (RAWINPUTDEVICELIST)Marshal.PtrToStructure(new IntPtr(pRawInputDeviceList.ToInt32() + (cbSize * i)), typeof(RAWINPUTDEVICELIST));

                    uint pcbSize = 0;
                    WinApi.GetRawInputDeviceInfo(rid.hDevice, 0x2000000b, IntPtr.Zero, ref pcbSize);                    //Get the size required in memory
                    IntPtr pData = Marshal.AllocHGlobal((int)pcbSize);
                    WinApi.GetRawInputDeviceInfo(rid.hDevice, 0x2000000b, pData, ref pcbSize);
                    var device = (RID_DEVICE_INFO)Marshal.PtrToStructure(pData, typeof(RID_DEVICE_INFO));
                    if (device.dwType == 0)
                    {
                        //Mouse
                        Logger.WriteLine($"Found mouse. Mouse ID = {device.mouse.dwId}, number of buttons = {device.mouse.dwNumberOfButtons}, sample rate = {device.mouse.dwSampleRate}, has horizontal wheel = {device.mouse.dwSampleRate}");
                    }
                    else if (device.dwType == 1)
                    {
                        //Keyboard
                        Logger.WriteLine($"Found keyboard. Keyboard type = {device.keyboard.dwType}, keyboard subtype = {device.keyboard.dwSubType}, scan code mode = {device.keyboard.dwKeyboardMode}, number of keys = {device.keyboard.dwNumberOfKeysTotal}");
                    }
                    yield return(device, rid.hDevice);
                }

                Marshal.FreeHGlobal(pRawInputDeviceList);
            }
        }
Exemple #3
0
        public static uint GetRawInputDeviceList(IList <RAWINPUTDEVICELIST> devices)
        {
            devices.Clear();

            uint uNumDevices = 0;
            int  structSize  = Marshal.SizeOf <RAWINPUTDEVICELIST>();

            unsafe
            {
                GetRawInputDeviceList(IntPtr.Zero, ref uNumDevices, structSize);
            }

            uint ret = 0;

            if (uNumDevices > 0)
            {
                IntPtr ptr = Marshal.AllocHGlobal(structSize * (int)uNumDevices);

                unsafe
                {
                    ret = GetRawInputDeviceList(ptr, ref uNumDevices, structSize);
                }

                for (int i = 0; i < uNumDevices; i++)
                {
                    RAWINPUTDEVICELIST rd = Marshal.PtrToStructure <RAWINPUTDEVICELIST>(IntPtr.Add(ptr, structSize * i));
                    devices.Add(rd);
                }

                Marshal.FreeHGlobal(ptr);
            }

            return(ret);
        }
Exemple #4
0
        public static RAWINPUTDEVICELIST[] GetInputDeviceList()
        {
            uint deviceCount = 0;
            int  size        = Marshal.SizeOf(typeof(RAWINPUTDEVICELIST));

            if (GetRawInputDeviceList(IntPtr.Zero, ref deviceCount, (uint)size) != 0)
            {
                throw new Exception("Failed to get raw input devices");
            }

            RAWINPUTDEVICELIST[] rawInputDevices = new RAWINPUTDEVICELIST[deviceCount + 1];
            if (deviceCount > 0)
            {
                IntPtr data = Marshal.AllocHGlobal((int)(size * deviceCount));
                try
                {
                    GetRawInputDeviceList(data, ref deviceCount, (uint)size);
                    for (int i = 0; i < deviceCount; i++)
                    {
                        RAWINPUTDEVICELIST rid = (RAWINPUTDEVICELIST)Marshal.PtrToStructure(
                            new IntPtr((data.ToInt32() + (size * i))), typeof(RAWINPUTDEVICELIST));
                        rawInputDevices[i] = rid;
                    }
                }
                finally
                {
                    Marshal.FreeHGlobal(data);
                }
            }
            return(rawInputDevices);
        }
        /// <summary>
        /// Function to retrieve the device name.
        /// </summary>
        /// <param name="device">Raw input device to gather information from.</param>
        /// <returns>A device name structure.</returns>
        private T GetDeviceInfo <T>(ref RAWINPUTDEVICELIST device)
            where T : class, IGorgonRawInputDeviceInfo
        {
            RID_DEVICE_INFO deviceInfo = RawInputApi.GetDeviceInfo(ref device);

            string deviceName = RawInputApi.GetDeviceName(ref device);

            if (string.IsNullOrWhiteSpace(deviceName))
            {
                return(null);
            }

            string className         = RawInputDeviceRegistryInfo.GetDeviceClass(deviceName, _log);
            string deviceDescription = RawInputDeviceRegistryInfo.GetDeviceDescription(deviceName, _log);

            switch (deviceInfo.dwType)
            {
            case RawInputType.Keyboard:
                return(new RawKeyboardInfo(device.Device, deviceName, className, deviceDescription, deviceInfo.keyboard) as T);

            case RawInputType.Mouse:
                return(new RawMouseInfo(device.Device, deviceName, className, deviceDescription, deviceInfo.mouse) as T);

            case RawInputType.HID:
                return(new GorgonRawHIDInfo(device.Device, deviceName, className, deviceDescription, deviceInfo.hid) as T);

            default:
                return(null);
            }
        }
Exemple #6
0
        public static Devices EnumerateDevices()
        {
            Devices foundDevices = Devices.None;
            uint    deviceCount  = 0;
            int     dwSize       = Marshal.SizeOf(typeof(RAWINPUTDEVICELIST));

            if (NativeMethods.GetRawInputDeviceList(IntPtr.Zero, ref deviceCount, (uint)dwSize) == 0)
            {
                IntPtr pRawInputDeviceList = Marshal.AllocHGlobal((int)(dwSize * deviceCount));
                using (new SafeUnmanagedMemoryHandle(pRawInputDeviceList))
                {
                    NativeMethods.GetRawInputDeviceList(pRawInputDeviceList, ref deviceCount, (uint)dwSize);

                    for (int i = 0; i < deviceCount; i++)
                    {
                        uint pSize = 0;

                        RAWINPUTDEVICELIST rid = (RAWINPUTDEVICELIST)Marshal.PtrToStructure(
                            IntPtr.Add(pRawInputDeviceList, dwSize * i),
                            typeof(RAWINPUTDEVICELIST));

                        NativeMethods.GetRawInputDeviceInfo(rid.hDevice, NativeMethods.RIDI_DEVICEINFO, IntPtr.Zero, ref pSize);
                        if (pSize <= 0)
                        {
                            continue;
                        }

                        IntPtr pInfo = Marshal.AllocHGlobal((int)pSize);
                        using (new SafeUnmanagedMemoryHandle(pInfo))
                        {
                            NativeMethods.GetRawInputDeviceInfo(rid.hDevice, NativeMethods.RIDI_DEVICEINFO, pInfo, ref pSize);
                            var info = (RID_DEVICE_INFO)Marshal.PtrToStructure(pInfo, typeof(RID_DEVICE_INFO));
                            switch (info.hid.usUsage)
                            {
                            case NativeMethods.TouchPadUsage:
                                foundDevices |= Devices.TouchPad;
                                break;

                            case NativeMethods.TouchScreenUsage:
                                foundDevices |= Devices.TouchScreen;
                                break;

                            case NativeMethods.PenUsage:
                                foundDevices |= Devices.Pen;
                                break;

                            default:
                                continue;
                            }
                        }
                    }
                }
                return(foundDevices);
            }
            else
            {
                throw new ApplicationException("Error!");
            }
        }
        public static bool Exists()
        {
            uint deviceListCount        = 0;
            uint rawInputDeviceListSize = (uint)Marshal.SizeOf <RAWINPUTDEVICELIST>();

            if (GetRawInputDeviceList(
                    null,
                    ref deviceListCount,
                    rawInputDeviceListSize) != 0)
            {
                return(false);
            }

            var devices = new RAWINPUTDEVICELIST[deviceListCount];

            if (GetRawInputDeviceList(
                    devices,
                    ref deviceListCount,
                    rawInputDeviceListSize) != deviceListCount)
            {
                return(false);
            }

            foreach (var device in devices.Where(x => x.dwType == RIM_TYPEHID))
            {
                uint deviceInfoSize = 0;

                if (GetRawInputDeviceInfo(
                        device.hDevice,
                        RIDI_DEVICEINFO,
                        IntPtr.Zero,
                        ref deviceInfoSize) != 0)
                {
                    continue;
                }

                var deviceInfo = new RID_DEVICE_INFO {
                    cbSize = deviceInfoSize
                };

                if (GetRawInputDeviceInfo(
                        device.hDevice,
                        RIDI_DEVICEINFO,
                        ref deviceInfo,
                        ref deviceInfoSize) == unchecked ((uint)-1))
                {
                    continue;
                }

                if ((deviceInfo.hid.usUsagePage == TouchpadUsagePage) &&
                    (deviceInfo.hid.usUsage == TouchpadUsage))
                {
                    return(true);
                }
            }
            return(false);
        }
Exemple #8
0
        private static RAWINPUTDEVICELIST[] EnumerateDevices(RawInputDeviceType ty)
        {
            RAWINPUTDEVICELIST[] retVal = null;
            uint count = 0;
            int  res   = Function.GetRawInputDeviceList(retVal, ref count, (uint)Marshal.SizeOf(typeof(RAWINPUTDEVICELIST)));

            retVal = new RAWINPUTDEVICELIST[count];
            res    = Function.GetRawInputDeviceList(retVal, ref count, (uint)Marshal.SizeOf(typeof(RAWINPUTDEVICELIST)));

            return(retVal.Where(x => x.dwType == ty).ToArray());
        }
Exemple #9
0
        public static RAWINPUTDEVICELIST[] GetRawInputDeviceList()
        {
            uint nDevices = 0;

            int res = GetRawInputDeviceList(null, ref nDevices, Marshal.SizeOf(typeof(RAWINPUTDEVICELIST)));

            Debug.Assert(res == 0);

            RAWINPUTDEVICELIST[] deviceList = new RAWINPUTDEVICELIST[nDevices];

            uint size = nDevices * (uint)Marshal.SizeOf(typeof(RAWINPUTDEVICELIST));

            res = GetRawInputDeviceList(deviceList, ref size, Marshal.SizeOf(typeof(RAWINPUTDEVICELIST)));
            Debug.Assert(res == nDevices);
            return(deviceList);
        }
Exemple #10
0
        private IEnumerable <RAWINPUTDEVICELIST> GetRawInputDevices(uint type)
        {
            uint deviceCount = 0;
            uint dwSize      = (uint)Marshal.SizeOf(typeof(RAWINPUTDEVICELIST));

            uint retValue = GetRawInputDeviceList(null, ref deviceCount, dwSize);

            if (0 != retValue)
            {
                return(null);
            }

            RAWINPUTDEVICELIST[] deviceList = new RAWINPUTDEVICELIST[deviceCount];

            retValue = GetRawInputDeviceList(deviceList, ref deviceCount, dwSize);

            return(deviceList.Where(ridl => ridl.dwType == type));
        }
Exemple #11
0
        public static IEnumerable <Device> GetDevices()
        {
            uint deviceCount = 0;

            var result = Win32.Function.GetRawInputDeviceList(null, ref deviceCount, (uint)Marshal.SizeOf(typeof(RAWINPUTDEVICELIST)));

            if (result == -1)
            {
                throw new Exception("Error executing GetRawInputDeviceList.");
            }

            RAWINPUTDEVICELIST[] rawInputDevices;

            do
            {
                rawInputDevices = new RAWINPUTDEVICELIST[deviceCount];

                result = Win32.Function.GetRawInputDeviceList(rawInputDevices, ref deviceCount, (uint)Marshal.SizeOf(typeof(RAWINPUTDEVICELIST)));
                if (result == -1)
                {
                    throw new Exception("Error executing GetRawInputDeviceList.");
                }
            } while (result != deviceCount);

            foreach (var rawInputDevice in rawInputDevices)
            {
                Device device;

                try
                {
                    device = new Device(rawInputDevice.hDevice);
                }
                catch
                {
                    continue;
                }

                yield return(device);
            }
        }
Exemple #12
0
        public static List <Device> GetHidDevices()
        {
            List <Device> devices = new List <Device>();

            //Get our list of devices
            RAWINPUTDEVICELIST[] ridList = null;
            uint deviceCount             = 0;
            int  res = Function.GetRawInputDeviceList(ridList, ref deviceCount, (uint)Marshal.SizeOf(typeof(RAWINPUTDEVICELIST)));

            if (res == -1)
            {
                //Just give up then
                return(devices);
            }

            ridList = new RAWINPUTDEVICELIST[deviceCount];
            res     = Function.GetRawInputDeviceList(ridList, ref deviceCount, (uint)Marshal.SizeOf(typeof(RAWINPUTDEVICELIST)));
            if (res != deviceCount)
            {
                //Just give up then
                return(devices);
            }

            foreach (RAWINPUTDEVICELIST device in ridList)
            {
                Device hidDevice;
                //Try create our HID device.
                try
                {
                    hidDevice = new Device(device.hDevice);
                }
                catch /*(System.Exception ex)*/
                {
                    //Just skip that device then
                    continue;
                }
                devices.Add(hidDevice);
            }
            return(devices);
        }
Exemple #13
0
        public static IList <Device> GetDevices()
        {
            // Get our list of devices
            RAWINPUTDEVICELIST[] ridList = null;
            uint deviceCount             = 0;
            int  res = Win32.Win32RawInput.NativeMethods.GetRawInputDeviceList(ridList, ref deviceCount, (uint)Marshal.SizeOf(typeof(RAWINPUTDEVICELIST)));

            if (res == -1)
            {
                // Just give up then
                return(null);
            }

            ridList = new RAWINPUTDEVICELIST[deviceCount];
            res     = Win32.Win32RawInput.NativeMethods.GetRawInputDeviceList(ridList, ref deviceCount, (uint)Marshal.SizeOf(typeof(RAWINPUTDEVICELIST)));
            if (res != deviceCount)
            {
                // Just give up then
                return(null);
            }

            var devs = new List <Device>();

            // For each our device add a node to our treeview
            foreach (RAWINPUTDEVICELIST device in ridList)
            {
                // Try create our HID device.
                try
                {
                    devs.Add(new Device(device.hDevice));
                }
                catch
                {
                    continue;
                }
            }

            return(devs);
        }
Exemple #14
0
        public HidDevice[] ListDevices()
        {
            uint deviceCount = 0;
            //get device count
            var res = RawInput.GetRawInputDeviceList(null, ref deviceCount, (uint)Marshal.SizeOf(typeof(RAWINPUTDEVICELIST)));

            if (res == unchecked ((uint)-1))
            {
                return(new HidDevice[0]);
            }

            var ridList = new RAWINPUTDEVICELIST[deviceCount];

            //get device list
            res = RawInput.GetRawInputDeviceList(ridList, ref deviceCount, (uint)Marshal.SizeOf(typeof(RAWINPUTDEVICELIST)));
            if (res != deviceCount)
            {
                return(new HidDevice[0]);
            }

            var hidDevices = ridList.Select(x =>
            {
                try
                {
                    if (CreateHidDevice(x.hDevice, out var hidDevice, out var error))
                    {
                        return(hidDevice);
                    }
                }
                catch (Exception ex)
                {
                }

                return(default(HidDevice));
            }).Where(x => x != default(HidDevice));

            return(hidDevices.ToArray());
        }
Exemple #15
0
        public static RAWINPUTDEVICELIST[] GetDeviceList()
        {
            Int32 numDevices = 0;
            Int32 SIZE       = Marshal.SizeOf(typeof(RAWINPUTDEVICELIST));

            if (GetRawInputDeviceList(IntPtr.Zero, ref numDevices, SIZE) == -1)
            {
                return(null);
            }

            IntPtr buffer = Marshal.AllocHGlobal(numDevices * SIZE);

            Int32 result = GetRawInputDeviceList(buffer, ref numDevices, SIZE);

            RAWINPUTDEVICELIST[] devices = new RAWINPUTDEVICELIST[result];
            foreach (var value in Enumerable.Range(0, result))
            {
                devices[value] = (RAWINPUTDEVICELIST)Marshal.PtrToStructure(
                    new IntPtr((buffer.ToInt64() + (SIZE * value))), typeof(RAWINPUTDEVICELIST));
            }

            return(devices);
        }
Exemple #16
0
        /// <summary>
        /// Rebuild the <see cref="EnumeratedDevices"/> list by querying for currently attached hardware.
        /// </summary>
        /// <returns>List of available devices, same as <see cref="EnumeratedDevices"/></returns>
        public IEnumerable <Device> EnumerateDevices()
        {
            // Remove devices
            foreach (IntPtr hDevice in _devices.Keys)
            {
                _EnumerateRemove(hDevice);
            }

            // Populate list of current devices
            uint numDevices = 0;

            if (0 > GetRawInputDeviceList(null, ref numDevices, (uint)(Marshal.SizeOf(typeof(RAWINPUTDEVICELIST)))))
            {
                throw new Exception("Bad return value from Win32 function");
            }
            if (numDevices <= 0)
            {
                return(EnumeratedDevices);
            }
            var ridList = new RAWINPUTDEVICELIST[numDevices];

            if (0 >= GetRawInputDeviceList(ridList, ref numDevices, (uint)(Marshal.SizeOf(typeof(RAWINPUTDEVICELIST)))))
            {
                throw new Exception("Bad return value from Win32 function");
            }

            // Add devices, looping through each struct in the array
            foreach (RAWINPUTDEVICELIST rid in ridList)
            {
                if (rid.dwType >= 0 && rid.dwType <= RIM_TYPEMAX && rid.hDevice != null)
                {
                    _EnumerateAdd(rid.hDevice);
                }
            }
            return(EnumeratedDevices);
        }
Exemple #17
0
        /// <summary>
        /// TODO: Find a way to cache that
        /// </summary>g
        private void PopulateDeviceList()
        {
            if (Device.Items != null && Device.Items.Count != 0)
            {
                // Keep using that list
                return;
            }

            Device.Items = new List <object>();

            // TODO: Add any option to disable device check

            //Get our list of devices
            RAWINPUTDEVICELIST[] ridList = null;
            uint deviceCount             = 0;
            int  res = Function.GetRawInputDeviceList(ridList, ref deviceCount, (uint)Marshal.SizeOf(typeof(RAWINPUTDEVICELIST)));

            if (res == -1)
            {
                //Just give up then
                return;
            }

            ridList = new RAWINPUTDEVICELIST[deviceCount];
            res     = Function.GetRawInputDeviceList(ridList, ref deviceCount, (uint)Marshal.SizeOf(typeof(RAWINPUTDEVICELIST)));
            if (res != deviceCount)
            {
                //Just give up then
                return;
            }

            //For each our device add a node to our treeview
            foreach (RAWINPUTDEVICELIST device in ridList)
            {
                Hid.Device.Input hidDevice;

                //Try create our HID device.
                try
                {
                    hidDevice = new SharpLib.Hid.Device.Input(device.hDevice);
                }
                catch /*(System.Exception ex)*/
                {
                    //Just skip that device then
                    continue;
                }

                // Allow derived class to filter devices
                if (IsSupportedDevice(hidDevice))
                {
                    // Use the device object itself
                    Device.Items.Add(hidDevice);
                }
            }

            // Sort them by friendly name
            Device.Items.Sort(delegate(object x, object y)
            {
                return(((Hid.Device.Input)x).FriendlyName.CompareTo(((Hid.Device.Input)y).FriendlyName));
            });

            CheckDeviceExistance();
        }
Exemple #18
0
        public int LoadDevices()
        {
            uint deviceCount = 0;
            int  dwSize      = (Marshal.SizeOf(typeof(RAWINPUTDEVICELIST)));

            uint result = Win32RawInput.GetRawInputDeviceList(IntPtr.Zero, ref deviceCount, dwSize);

            if (result != 0)
            {
                throw new Win32Exception("Failed to get raw input devices");
            }

            IntPtr pRawInputDeviceList = Marshal.AllocHGlobal((int)(dwSize * deviceCount));

            Win32RawInput.GetRawInputDeviceList(pRawInputDeviceList, ref deviceCount, dwSize);

            for (int i = 0; i < deviceCount; i++)
            {
                //DeviceInfo dInfo;
                //string deviceName;
                //uint pcbSize = 0;

                IntPtr             ptr = new IntPtr(pRawInputDeviceList.ToInt64() + (dwSize * i));
                RAWINPUTDEVICELIST rid = (RAWINPUTDEVICELIST)Marshal.PtrToStructure(ptr, typeof(RAWINPUTDEVICELIST));

                string deviceName = Win32RawInput.GetDeviceName(rid.hDevice);

                // Drop the "root" keyboard and mouse devices used for Terminal Services and the Remote Desktop.
                if (!String.IsNullOrEmpty(deviceName) && !deviceName.ToUpper().Contains("ROOT"))
                {
                    switch ((RIM)rid.dwType)
                    {
                    case RIM.TYPEMOUSE:
                    case RIM.TYPEKEYBOARD:
                    case RIM.TYPEHID:
                        DeviceInfo dInfo = new DeviceInfo()
                        {
                            DeviceName   = deviceName,
                            DeviceHandle = rid.hDevice,
                            DeviceType   = (RIM)rid.dwType,
                        };

                        var additionalInfo = ReadRegisty(deviceName);

                        if (additionalInfo.ContainsKey("DeviceDesc"))
                        {
                            dInfo.Name = additionalInfo["DeviceDesc"];
                        }

                        if (additionalInfo.ContainsKey("Class"))
                        {
                            string deviceClass = additionalInfo["Class"] ?? "";

                            switch (deviceClass.ToUpper())
                            {
                            case "KEYBOARD":
                                if (!keyboards.Contains(dInfo))
                                {
                                    keyboards.Add(dInfo);
                                    deviceCount++;
                                }
                                break;

                            case "MOUSE":
                                if (!mice.Contains(dInfo))
                                {
                                    mice.Add(dInfo);
                                    deviceCount++;
                                }
                                break;

                            default:
                                if (!otherDevices.Contains(dInfo))
                                {
                                    otherDevices.Add(dInfo);
                                    deviceCount++;
                                }
                                break;
                            }
                        }
                        deviceCount++;
                        break;
                    }
                }

                /*
                 * if (!String.IsNullOrEmpty(deviceName) && !deviceName.ToUpper().Contains("ROOT"))
                 * {
                 *  switch ((RIM)rid.dwType)
                 *  {
                 *      case RIM.TYPEMOUSE:
                 *      case RIM.TYPEKEYBOARD:
                 *      case RIM.TYPEHID:
                 *          DeviceInfo dInfo = new DeviceInfo();
                 *
                 *          dInfo.DeviceName = deviceName;
                 *          dInfo.DeviceHandle = rid.hDevice;
                 *          dInfo.DeviceType = GetDeviceType(rid.dwType);
                 *
                 *          var additionalInfo = ReadRegisty(deviceName);
                 *          dInfo.Name = additionalInfo["DeviceDesc"];
                 *
                 *          switch (additionalInfo["Class"].ToUpper())
                 *          {
                 *              case "KEYBOARD":
                 *                  if (!keyboards.Contains(dInfo))
                 *                  {
                 *                      keyboards.Add(dInfo);
                 *                      deviceCount++;
                 *                  }
                 *                  break;
                 *              case "MOUSE":
                 *                  if (!mice.Contains(dInfo))
                 *                  {
                 *                      mice.Add(dInfo);
                 *                      deviceCount++;
                 *                  }
                 *                  break;
                 *              default:
                 *                  if (!otherDevices.Contains(dInfo))
                 *                  {
                 *                      otherDevices.Add(dInfo);
                 *                      deviceCount++;
                 *                  }
                 *                  break;
                 *          }
                 *          deviceCount++;
                 *          break;
                 *  }
                 * }
                 */

                /*
                 *
                 * Win32RawInput.GetRawInputDeviceInfo(rid.hDevice, RIDI.DEVICENAME, IntPtr.Zero, ref pcbSize);
                 * if (pcbSize > 0)
                 * {
                 *
                 *  Win32RawInput.GetRawInputDeviceInfo(rid.hDevice, RIDI.DEVICENAME, pData, ref pcbSize);
                 *  deviceName = (string)Marshal.PtrToStringAnsi(pData);
                 *
                 *  // Drop the "root" keyboard and mouse devices used for Terminal
                 *  // Services and the Remote Desktop
                 *  if (deviceName.ToUpper().Contains("ROOT"))
                 *  {
                 *      continue;
                 *  }
                 *
                 *  // If the device is identified in the list as a keyboard or
                 *  // HID device, create a DeviceInfo object to store information
                 *  // about it
                 *  if (rid.dwType == (int)RIM.TYPEMOUSE || rid.dwType == (int)RIM.TYPEKEYBOARD || rid.dwType == (int)RIM.TYPEHID)
                 *  {
                 *      dInfo = new DeviceInfo();
                 *
                 *      dInfo.DeviceName = (string)Marshal.PtrToStringAnsi(pData);
                 *      dInfo.DeviceHandle = rid.hDevice;
                 *      dInfo.DeviceType = GetDeviceType(rid.dwType);
                 *
                 *      var additionalInfo = ReadRegisty(deviceName);
                 *      dInfo.Name = additionalInfo["DeviceDesc"];
                 *
                 *      switch (additionalInfo["Class"].ToUpper())
                 *      {
                 *          case "KEYBOARD":
                 *              if (!keyboards.Contains(dInfo))
                 *              {
                 *                  keyboards.Add(dInfo);
                 *                  deviceCount++;
                 *              }
                 *              break;
                 *          case "MOUSE":
                 *              if (!mice.Contains(dInfo))
                 *              {
                 *                  mice.Add(dInfo);
                 *                  deviceCount++;
                 *              }
                 *              break;
                 *          default:
                 *              if (!otherDevices.Contains(dInfo))
                 *              {
                 *                  otherDevices.Add(dInfo);
                 *                  deviceCount++;
                 *              }
                 *              break;
                 *      }
                 *      deviceCount++;
                 *  }
                 *  Marshal.FreeHGlobal(pData);
                 * }
                 */
            }
            Marshal.FreeHGlobal(pRawInputDeviceList);
            return((int)deviceCount);
        }
Exemple #19
0
        /// <summary>
        /// Iterates through the list provided by GetRawInputDeviceList,
        /// counting keyboard devices and adding them to deviceList.
        /// </summary>
        /// <returns>The number of keyboard devices found.</returns>
        public int EnumerateDevices()
        {
            int  NumberOfDevices = 0;
            uint deviceCount     = 0;
            int  dwSize          = (Marshal.SizeOf(typeof(RAWINPUTDEVICELIST)));

            if (GetRawInputDeviceList(IntPtr.Zero, ref deviceCount, (uint)dwSize) == 0)
            {
                IntPtr pRawInputDeviceList = Marshal.AllocHGlobal((int)(dwSize * deviceCount));
                GetRawInputDeviceList(pRawInputDeviceList, ref deviceCount, (uint)dwSize);

                for (int i = 0; i < deviceCount; i++)
                {
                    uint pcbSize = 0;

                    RAWINPUTDEVICELIST rid = (RAWINPUTDEVICELIST)Marshal.PtrToStructure(
                        new IntPtr((pRawInputDeviceList.ToInt32() + (dwSize * i))),
                        typeof(RAWINPUTDEVICELIST));

                    GetRawInputDeviceInfo(rid.hDevice, RIDI_DEVICENAME, IntPtr.Zero, ref pcbSize);

                    if (pcbSize > 0)
                    {
                        IntPtr pData = Marshal.AllocHGlobal((int)pcbSize);
                        GetRawInputDeviceInfo(rid.hDevice, RIDI_DEVICENAME, pData, ref pcbSize);
                        string deviceName = Marshal.PtrToStringAnsi(pData);

                        //The list will include the "root" keyboard and mouse devices
                        //which appear to be the remote access devices used by Terminal
                        //Services or the Remote Desktop - we're not interested in these
                        //so the following code with drop into the next loop iteration
                        if (deviceName.ToUpper().Contains("ROOT"))
                        {
                            continue;
                        }

                        //If the device is identified as a keyboard or HID device,
                        //create a DeviceInfo object to store information about it
                        if (rid.dwType == RIM_TYPEKEYBOARD || rid.dwType == RIM_TYPEHID)
                        {
                            DeviceInfo dInfo = new DeviceInfo();

                            dInfo.deviceName   = Marshal.PtrToStringAnsi(pData);
                            dInfo.deviceHandle = rid.hDevice;
                            dInfo.deviceType   = GetDeviceType(rid.dwType);

                            //Check the Registry to see whether this is actually a
                            //keyboard.
                            bool IsKeyboardDevice = false;

                            string DeviceDesc = ReadReg(deviceName, ref IsKeyboardDevice);
                            dInfo.Name = DeviceDesc;

                            //If it is a keyboard and it isn't already in the list,
                            //add it to the deviceList hashtable and increase the
                            //NumberOfDevices count
                            if (!deviceList.Contains(rid.hDevice) && IsKeyboardDevice)
                            {
                                NumberOfDevices++;
                                deviceList.Add(rid.hDevice, dInfo);
                            }
                        }
                        Marshal.FreeHGlobal(pData);
                    }
                }

                Marshal.FreeHGlobal(pRawInputDeviceList);
                return(NumberOfDevices);
            }
            else
            {
                throw new ApplicationException("Error!");
            }
        }
Exemple #20
0
        public bool CardReaderIdentifier(string vidStrg, string pidStrg, string optionalStrg)
        {
            uint deviceCount = 0;
            uint apiOpt;
            int  dwSize      = (Marshal.SizeOf(typeof(RAWINPUTDEVICELIST)));
            bool devicefound = false;

            if (vidStrg == "")
            {
                vidStrg = "VID_1243";
            }
            if (pidStrg == "")
            {
                pidStrg = "PID_E000";
            }
            if (optionalStrg == "")
            {
                optionalStrg = "MI_00";
            }
            if (GetRawInputDeviceList(IntPtr.Zero, ref deviceCount, (uint)dwSize) != 0)
            {
                throw new ApplicationException("An error occurred while retrieving the list of devices. Error in GetRawInputDeviceList. Detailed Error is " + ProcessLastError());
            }
            IntPtr pRawInputDeviceList = Marshal.AllocHGlobal((int)(dwSize * deviceCount));

            if (pRawInputDeviceList == null)
            {
                throw new ApplicationException("Memory allocation failed");
            }

            apiOpt = GetRawInputDeviceList(pRawInputDeviceList, ref deviceCount, (uint)dwSize);
            if (apiOpt < 0)
            {
                throw new ApplicationException("Could not fetch raw device list. Failure in GetRawInputDeviceList - Second call. Detailed Error is " + ProcessLastError());
            }

            for (uint devCount = 0; devCount < deviceCount; devCount++)
            {
                string deviceName;
                uint   pcbSize = 0;

                RAWINPUTDEVICELIST rid = (RAWINPUTDEVICELIST)Marshal.PtrToStructure(
                    new IntPtr((pRawInputDeviceList.ToInt32() + (dwSize * devCount))),
                    typeof(RAWINPUTDEVICELIST));

                GetRawInputDeviceInfo(rid.hDevice, RIDI_DEVICENAME, IntPtr.Zero, ref pcbSize);

                if (pcbSize > 0)
                {
                    IntPtr pData = Marshal.AllocHGlobal((int)pcbSize);
                    GetRawInputDeviceInfo(rid.hDevice, RIDI_DEVICENAME, pData, ref pcbSize);
                    deviceName = (string)Marshal.PtrToStringAnsi(pData);
                    String upperCasedeviceName = deviceName.ToUpper();
                    //if (rid.dwType == RIM_TYPEKEYBOARD)
                    {
                        if (upperCasedeviceName.Contains(vidStrg) && upperCasedeviceName.Contains(pidStrg) && upperCasedeviceName.Contains(optionalStrg))
                        {
                            //MessageBox.Show(deviceName);
                            if (devicefound == false)
                            {
                                devicefound        = true;
                                dInfo              = new DeviceInfo();
                                dInfo.deviceName   = deviceName;
                                dInfo.deviceHandle = rid.hDevice;
                                dInfo.deviceType   = GetDeviceType(rid.dwType);
                                dInfo.Name         = deviceName;
                            }
                            else
                            {
                                throw new ApplicationException("Multiple card readers have been found with the same vendor and product id");
                            }
                        }
                    }
                    Marshal.FreeHGlobal(pData);
                }
            }
            Marshal.FreeHGlobal(pRawInputDeviceList);
            return(devicefound);
        }
Exemple #21
0
        public static RAWINPUTDEVICELIST[] GetRawInputDeviceList()
        {
            uint nDevices = 0;

            int res = GetRawInputDeviceList(null, ref nDevices, Marshal.SizeOf(typeof(RAWINPUTDEVICELIST)));
            Debug.Assert(res == 0);

            RAWINPUTDEVICELIST[] deviceList = new RAWINPUTDEVICELIST[nDevices];

            uint size = nDevices * (uint)Marshal.SizeOf(typeof(RAWINPUTDEVICELIST));
            res = GetRawInputDeviceList(deviceList, ref size, Marshal.SizeOf(typeof(RAWINPUTDEVICELIST)));
            Debug.Assert(res == nDevices);
            return deviceList;
        }
        /// <summary>
        /// Iterates through the list provided by GetRawInputDeviceList,
        /// counting keyboard devices and adding them to deviceList.
        /// </summary>
        /// <returns>The number of keyboard devices found.</returns>
        public int EnumerateDevices()
        {
            lock (_deviceList)
            {
                int  NumberOfDevices = 0;
                uint deviceCount     = 0;
                int  dwSize          = (Marshal.SizeOf(typeof(RAWINPUTDEVICELIST)));
                _deviceList.Clear();

                // Get the number of raw input devices in the list,
                // then allocate sufficient memory and get the entire list
                if (GetRawInputDeviceList(IntPtr.Zero, ref deviceCount, (uint)dwSize) == 0)
                {
                    IntPtr pRawInputDeviceList = Marshal.AllocHGlobal((int)(dwSize * deviceCount));
                    GetRawInputDeviceList(pRawInputDeviceList, ref deviceCount, (uint)dwSize);

                    // Iterate through the list, discarding undesired items
                    // and retrieving further information on keyboard devices
                    for (int i = -1; i < deviceCount; i++)
                    {
                        DeviceInfo dInfo;
                        string     deviceName;
                        uint       pcbSize = 0;

                        IntPtr          hDevice    = IntPtr.Zero;
                        int             deviceType = 0;
                        RID_DEVICE_INFO deviceInfo = new RID_DEVICE_INFO();

                        if (i == -1)
                        {
                            dInfo = new DeviceInfo();

                            dInfo.DeviceName   = "SendInput";
                            dInfo.DeviceHandle = IntPtr.Zero;
                            dInfo.DeviceType   = DeviceType.Keyboard;
                            dInfo.Name         = "SendInput (Keystrokes simulated by applications)";

                            NumberOfDevices++;
                            _deviceList.Add(IntPtr.Zero, dInfo);
                            continue;
                        }

                        RAWINPUTDEVICELIST rid = (RAWINPUTDEVICELIST)Marshal.PtrToStructure(
                            new IntPtr((pRawInputDeviceList.ToInt32() + (dwSize * i))),
                            typeof(RAWINPUTDEVICELIST));
                        hDevice    = rid.hDevice;
                        deviceType = rid.dwType;

                        GetRawInputDeviceInfo(hDevice, RIDI_DEVICENAME, IntPtr.Zero, ref pcbSize);

                        if (pcbSize > 0)
                        {
                            IntPtr pData = Marshal.AllocHGlobal((int)pcbSize);
                            GetRawInputDeviceInfo(hDevice, RIDI_DEVICENAME, pData, ref pcbSize);
                            deviceName = (string)Marshal.PtrToStringAnsi(pData);
                            Marshal.FreeHGlobal(pData);

                            // Drop the "root" keyboard and mouse devices used for Terminal
                            // Services and the Remote Desktop
                            if (deviceName.ToUpper().StartsWith(@"\\?\ROOT"))
                            {
                                continue;
                            }
                            if (deviceName.ToUpper().StartsWith(@"\??\ROOT"))
                            {
                                continue;
                            }

                            GetRawInputDeviceInfo(hDevice, RIDI_DEVICEINFO, IntPtr.Zero, ref pcbSize);

                            string bits = "";

                            if (pcbSize > 0)
                            {
                                pData = Marshal.AllocHGlobal((int)pcbSize);
                                GetRawInputDeviceInfo(hDevice, RIDI_DEVICEINFO, pData, ref pcbSize);

                                var data = new byte[pcbSize];
                                Marshal.Copy(pData, data, 0, (int)pcbSize);
                                bits = BitConverter.ToString(data);

                                deviceInfo = (RID_DEVICE_INFO)Marshal.PtrToStructure(pData, typeof(RID_DEVICE_INFO));
                                Marshal.FreeHGlobal(pData);
                            }

                            // If the device is identified in the list as a keyboard or
                            // HID device, create a DeviceInfo object to store information
                            // about it
                            //if (rid.dwType == RIM_TYPEKEYBOARD || rid.dwType == RIM_TYPEHID)
                            {
                                dInfo = new DeviceInfo();

                                dInfo.DeviceHandle       = hDevice;
                                dInfo.DeviceType         = GetDeviceType(deviceType);
                                dInfo.DeviceName         = deviceName;
                                dInfo.RawInputDeviceInfo = deviceInfo;

                                // Check the Registry to see whether this is actually a
                                // keyboard, and to retrieve a more friendly description.
                                bool IsKeyboardDevice = false;
                                dInfo.DeviceDesc = ReadReg(deviceName, ref IsKeyboardDevice);
                                dInfo.Name       = dInfo.DeviceDesc.Substring(dInfo.DeviceDesc.LastIndexOf(";") + 1);

                                // If it is a keyboard and it isn't already in the list,
                                // add it to the deviceList hashtable and increase the
                                // NumberOfDevices count
                                //if (!deviceList.Contains(hDevice) && IsKeyboardDevice)
                                if (!_deviceList.ContainsKey(hDevice))
                                {
                                    NumberOfDevices++;
                                    _deviceList.Add(hDevice, dInfo);
                                }
                            }
                        }
                    }


                    Marshal.FreeHGlobal(pRawInputDeviceList);

                    return(NumberOfDevices);
                }
                else
                {
                    throw new ApplicationException("An error occurred while retrieving the list of devices.");
                }
            }
        }
        /// <summary>
        /// Iterates through the list provided by GetRawInputDeviceList,
        /// counting 3Dx devices and adding them to deviceList.
        /// </summary>
        /// <returns>The number of 3Dx devices found.</returns>
        public int EnumerateDevices()
        {
            int  NumberOfDevices = 0;
            uint deviceCount     = 0;
            int  dwSize          = (Marshal.SizeOf(typeof(RAWINPUTDEVICELIST)));

            if (GetRawInputDeviceList(IntPtr.Zero, ref deviceCount, (uint)dwSize) == 0)
            {
                IntPtr pRawInputDeviceList = Marshal.AllocHGlobal((int)(dwSize * deviceCount));
                GetRawInputDeviceList(pRawInputDeviceList, ref deviceCount, (uint)dwSize);

                for (int i = 0; i < deviceCount; i++)
                {
                    uint pcbSize = 0;

                    RAWINPUTDEVICELIST rid = (RAWINPUTDEVICELIST)Marshal.PtrToStructure(
                        new IntPtr((pRawInputDeviceList.ToInt32() + (dwSize * i))),
                        typeof(RAWINPUTDEVICELIST));

                    GetRawInputDeviceInfo(rid.hDevice, RIDI_DEVICENAME, IntPtr.Zero, ref pcbSize);

                    if (pcbSize > 0)
                    {
                        IntPtr pData = Marshal.AllocHGlobal((int)pcbSize);
                        GetRawInputDeviceInfo(rid.hDevice, RIDI_DEVICENAME, pData, ref pcbSize);
                        string deviceName = Marshal.PtrToStringAnsi(pData);

                        //If the device is identified as a HID device with usagePage 1, usage 8,
                        //create a DeviceInfo object to store information about it
                        if (rid.dwType == RIM_TYPEHID)
                        {
                            DeviceInfo dInfo = new DeviceInfo();

                            // Create an object to set the size in the struct.  Then marshall it to a ptr to pass to RI.
                            RID_DEVICE_INFO_HID hidInfo = new RID_DEVICE_INFO_HID();
                            int dwHidInfoSize           = Marshal.SizeOf(hidInfo);
                            hidInfo.cbSize = dwHidInfoSize;
                            IntPtr pHIDData = Marshal.AllocHGlobal(dwHidInfoSize);
                            Marshal.StructureToPtr(hidInfo, pHIDData, true);

                            uint uHidInfoSize = (uint)dwHidInfoSize;

                            GetRawInputDeviceInfo(rid.hDevice, RIDI_DEVICEINFO, pHIDData, ref uHidInfoSize);

                            // Marshal back to an object to retrieve info
                            hidInfo = (RID_DEVICE_INFO_HID)Marshal.PtrToStructure(pHIDData, typeof(RID_DEVICE_INFO_HID));

                            dInfo.deviceName   = Marshal.PtrToStringAnsi(pData);
                            dInfo.deviceHandle = rid.hDevice;


                            //If it is a 3Dx device and it isn't already in the list,
                            //add it to the deviceList hashtable and increase the
                            //NumberOfDevices count
                            if (Is3DxDevice(hidInfo) && !deviceList.Contains(rid.hDevice))
                            {
                                Console.WriteLine("Using 3Dx device: " + deviceName);
                                NumberOfDevices++;
                                deviceList.Add(rid.hDevice, dInfo);
                            }
                            Marshal.FreeHGlobal(pHIDData);
                        }
                        Marshal.FreeHGlobal(pData);
                    }
                }

                Marshal.FreeHGlobal(pRawInputDeviceList);
                return(NumberOfDevices);
            }
            else
            {
                throw new ApplicationException("Error!");
            }
        }
        private void EnumerateDevices()
        {
            uint deviceCount = 0;
            int  dwSize      = Marshal.SizeOf(typeof(RAWINPUTDEVICELIST));

            if (NativeMethods.GetRawInputDeviceList(IntPtr.Zero, ref deviceCount, (uint)dwSize) == 0)
            {
                IntPtr pRawInputDeviceList = Marshal.AllocHGlobal((int)(dwSize * deviceCount));
                using (new SafeUnmanagedMemoryHandle(pRawInputDeviceList))
                {
                    _validDevices.Clear();

                    NativeMethods.GetRawInputDeviceList(pRawInputDeviceList, ref deviceCount, (uint)dwSize);

                    for (int i = 0; i < deviceCount; i++)
                    {
                        RAWINPUTDEVICELIST rid = (RAWINPUTDEVICELIST)Marshal.PtrToStructure(new IntPtr(pRawInputDeviceList.ToInt64() + dwSize * i), typeof(RAWINPUTDEVICELIST));
                        if (rid.dwType != NativeMethods.RIM_TYPEHID)
                        {
                            continue;
                        }

                        uint pcbSize = 0;
                        NativeMethods.GetRawInputDeviceInfo(rid.hDevice, NativeMethods.RIDI_DEVICEINFO, IntPtr.Zero, ref pcbSize);
                        if (pcbSize <= 0)
                        {
                            continue;
                        }

                        IntPtr pInfo = Marshal.AllocHGlobal((int)pcbSize);
                        using (new SafeUnmanagedMemoryHandle(pInfo))
                        {
                            NativeMethods.GetRawInputDeviceInfo(rid.hDevice, NativeMethods.RIDI_DEVICEINFO, pInfo, ref pcbSize);
                            var info = (RID_DEVICE_INFO)Marshal.PtrToStructure(pInfo, typeof(RID_DEVICE_INFO));
                            if (info.hid.usUsage != NativeMethods.TouchPadUsage && info.hid.usUsage != NativeMethods.TouchScreenUsage)
                            {
                                continue;
                            }

                            NativeMethods.GetRawInputDeviceInfo(rid.hDevice, NativeMethods.RIDI_DEVICENAME, IntPtr.Zero, ref pcbSize);
                            if (pcbSize <= 0)
                            {
                                continue;
                            }

                            IntPtr pData = Marshal.AllocHGlobal((int)pcbSize);
                            using (new SafeUnmanagedMemoryHandle(pData))
                            {
                                NativeMethods.GetRawInputDeviceInfo(rid.hDevice, NativeMethods.RIDI_DEVICENAME, pData, ref pcbSize);
                                string deviceName = Marshal.PtrToStringAnsi(pData);

                                if (string.IsNullOrEmpty(deviceName) || deviceName.IndexOf("VIRTUAL_DIGITIZER", StringComparison.OrdinalIgnoreCase) >= 0 || deviceName.IndexOf("ROOT", StringComparison.OrdinalIgnoreCase) >= 0)
                                {
                                    continue;
                                }

                                _validDevices.Add(rid.hDevice, info.hid.usUsage);
                            }
                        }
                    }
                }
            }
            else
            {
                throw new ApplicationException("Error!");
            }
        }
    public int EnumerateDevices()
    {
        int result      = 0;
        int deviceCount = 0;
        int dwSize      = (System.Runtime.InteropServices.Marshal.SizeOf(typeof(RAWINPUTDEVICELIST)));

        if (GetRawInputDeviceList(System.IntPtr.Zero, ref deviceCount, dwSize) == 0)
        {
            System.IntPtr pRawInputDeviceList = System.Runtime.InteropServices.Marshal.AllocHGlobal(System.Convert.ToInt32(dwSize * deviceCount));
            GetRawInputDeviceList(pRawInputDeviceList, ref deviceCount, System.Convert.ToInt32(dwSize));
            for (long i = 0; i <= deviceCount - 1; i++)
            {
                DeviceNameInfo     dName      = default(DeviceNameInfo);
                string             deviceName = null;
                int                pcbSizeA   = 0;
                int                pcbSizeB   = 0;
                RAWINPUTDEVICELIST rid        = (RAWINPUTDEVICELIST)System.Runtime.InteropServices.Marshal.PtrToStructure(new System.IntPtr((pRawInputDeviceList.ToInt32() + (dwSize * i))), typeof(RAWINPUTDEVICELIST));
                GetRawInputDeviceInfo(rid.hDevice, RIDI_DEVICENAME, System.IntPtr.Zero, ref pcbSizeA);
                if (pcbSizeA > 0)
                {
                    System.IntPtr pDataA = System.Runtime.InteropServices.Marshal.AllocHGlobal(System.Convert.ToInt32(pcbSizeA));
                    GetRawInputDeviceInfo(rid.hDevice, RIDI_DEVICENAME, pDataA, ref pcbSizeA);
                    deviceName = (string)System.Runtime.InteropServices.Marshal.PtrToStringAnsi(pDataA);
                    // Drop the "root" keyboard and mouse devices used for Terminal Services and the Remote Desktop
                    if (!deviceName.ToUpper().Contains("ROOT"))
                    {
                        dName              = new DeviceNameInfo();
                        dName.deviceName   = (string)System.Runtime.InteropServices.Marshal.PtrToStringAnsi(pDataA);
                        dName.deviceHandle = rid.hDevice;
                        dName.deviceType   = GetDeviceType(rid.dwType);
                        GetRawInputDeviceInfo(rid.hDevice, RIDI_DEVICEINFO, System.IntPtr.Zero, ref pcbSizeB);
                        if (pcbSizeB > 0)
                        {
                            System.IntPtr pDataB = System.Runtime.InteropServices.Marshal.AllocHGlobal(System.Convert.ToInt32(pcbSizeB));
                            System.Runtime.InteropServices.Marshal.Copy(new int[] { pcbSizeB }, 0, pDataB, 1);
                            GetRawInputDeviceInfo(rid.hDevice, RIDI_DEVICEINFO, pDataB, ref pcbSizeB);
                            byte[] deviceInfoBuffer = new byte[pcbSizeB];
                            System.Runtime.InteropServices.Marshal.Copy(pDataB, deviceInfoBuffer, 0, pcbSizeB);
                            System.Runtime.InteropServices.Marshal.FreeHGlobal(pDataB);
                            DeviceInfo dInfo = new DeviceInfo();
                            dInfo.Size = System.BitConverter.ToInt32(deviceInfoBuffer, 0);
                            dInfo.Type = System.BitConverter.ToInt32(deviceInfoBuffer, 4);
                            int pcbSizeC = pcbSizeB - 8;
                            if (((dInfo.Type == RIM_TYPEKEYBOARD) && (pcbSizeC >= System.Runtime.InteropServices.Marshal.SizeOf(typeof(DeviceInfoKeyboard)))))
                            {
                                dInfo.KeyboardInfo.Type                 = System.BitConverter.ToUInt32(deviceInfoBuffer, 8);
                                dInfo.KeyboardInfo.SubType              = System.BitConverter.ToUInt32(deviceInfoBuffer, 12);
                                dInfo.KeyboardInfo.KeyboardMode         = System.BitConverter.ToUInt32(deviceInfoBuffer, 16);
                                dInfo.KeyboardInfo.NumberOfFunctionKeys = System.BitConverter.ToUInt32(deviceInfoBuffer, 20);
                                dInfo.KeyboardInfo.NumberOfIndicators   = System.BitConverter.ToUInt32(deviceInfoBuffer, 24);
                                dInfo.KeyboardInfo.NumberOfKeysTotal    = System.BitConverter.ToUInt32(deviceInfoBuffer, 28);
                            }
                            else if (((dInfo.Type == RIM_TYPEHID) && (pcbSizeC >= System.Runtime.InteropServices.Marshal.SizeOf(typeof(DeviceInfoHID)))))
                            {
                                dInfo.HIDInfo.VendorID      = System.BitConverter.ToUInt32(deviceInfoBuffer, 8);
                                dInfo.HIDInfo.ProductID     = System.BitConverter.ToUInt32(deviceInfoBuffer, 12);
                                dInfo.HIDInfo.VersionNumber = System.BitConverter.ToUInt32(deviceInfoBuffer, 16);
                                dInfo.HIDInfo.UsagePage     = System.BitConverter.ToUInt16(deviceInfoBuffer, 20);
                                dInfo.HIDInfo.Usage         = System.BitConverter.ToUInt16(deviceInfoBuffer, 22);
                                if (!m_usagePagesList.ContainsKey(dInfo.HIDInfo.UsagePage))
                                {
                                    m_usagePagesList.Add(dInfo.HIDInfo.UsagePage, dInfo.HIDInfo.UsagePage);
                                }
                            }
                            else if (((dInfo.Type == RIM_TYPEMOUSE) && (pcbSizeC >= System.Runtime.InteropServices.Marshal.SizeOf(typeof(DeviceInfoMouse)))))
                            {
                                dInfo.MouseInfo.ID = System.BitConverter.ToUInt32(deviceInfoBuffer, 8);
                                dInfo.MouseInfo.NumberOfButtons = System.BitConverter.ToUInt32(deviceInfoBuffer, 12);
                                dInfo.MouseInfo.SampleRate      = System.BitConverter.ToUInt32(deviceInfoBuffer, 16);
                            }
                            result += 1;
                            m_deviceInfoList.Add(rid.hDevice, dInfo);
                            m_deviceNameList.Add(rid.hDevice, dName);
                        }
                    }
                    System.Runtime.InteropServices.Marshal.FreeHGlobal(pDataA);
                }
            }
            System.Runtime.InteropServices.Marshal.FreeHGlobal(pRawInputDeviceList);
        }
        else
        {
            m_errorMessage = "An error occurred while retrieving the list of raw input devices.";
            result         = 0;
        }
        return(result);
    }
Exemple #26
0
        public static RAWINPUTDEVICELIST[] GetAllRawDevices()
        {
            uint deviceCount = 0;
            uint dwSize = (uint)Marshal.SizeOf(typeof(RAWINPUTDEVICELIST));

            // First call the system routine with a null pointer
            // for the array to get the size needed for the list
            uint retValue = GetRawInputDeviceList(IntPtr.Zero, ref deviceCount, dwSize);

            // If anything but zero is returned, the call failed, so return a null list
            if (0 != retValue)
                return null;

            // Now allocate an array of the specified number of entries
            RAWINPUTDEVICELIST[] deviceList = new RAWINPUTDEVICELIST[deviceCount];
            IntPtr pRawInputDeviceList = Marshal.AllocHGlobal((int)(dwSize * deviceCount));

            // Now make the call again, using the array
            GetRawInputDeviceList(pRawInputDeviceList, ref deviceCount, dwSize);

            // Fill up the array with the structures
            for (int i = 0; i < deviceCount; i++)
            {
                deviceList[i] = (RAWINPUTDEVICELIST)Marshal.PtrToStructure(
                    new IntPtr((pRawInputDeviceList.ToInt32() + (dwSize * i))),
                    typeof(RAWINPUTDEVICELIST));
            }

            // Free up the memory we first got the information into as
            // it is no longer needed, since the structures have been
            // copied to the deviceList array.
            Marshal.FreeHGlobal(pRawInputDeviceList);

            // Finally, return the filled in list
            return deviceList;
        }
Exemple #27
0
        /// <summary>
        /// Gets the raw input devices attached to the system.
        /// </summary>
        /// <returns></returns>
        public static unsafe RawDevice[] GetRawDevices()
        {
            uint numDevices = 0;

            uint res = Win32.GetRawInputDeviceList(IntPtr.Zero,
            ref numDevices, Win32.SIZEOF_RAWINPUTDEVICELIST);

            if (res != 0)
                throw new Win32Exception(Marshal.GetLastWin32Error());

            List<RawDevice> deviceList = new List<RawDevice>((int)numDevices);

            if (numDevices > 0)
            {
                RAWINPUTDEVICELIST[] rawDevices = new RAWINPUTDEVICELIST[numDevices];

                fixed (RAWINPUTDEVICELIST* pRawDevices = rawDevices)
                {
                    res = Win32.GetRawInputDeviceList((IntPtr)pRawDevices,
                    ref numDevices, Win32.SIZEOF_RAWINPUTDEVICELIST);

                    if (res != numDevices)
                        throw new Win32Exception(Marshal.GetLastWin32Error());
                }

                foreach (RAWINPUTDEVICELIST rawDevice in rawDevices)
                {
                    if (rawDevice.dwType == Win32.RIM_TYPEMOUSE)
                    {
                        // Terminal Server virtual mouse device.
                        if (GetDeviceName(rawDevice.hDevice).Contains("RDP_MOU"))
                            continue;
                    }
                    else if (rawDevice.dwType == Win32.RIM_TYPEKEYBOARD)
                    {
                        // Terminal Server virtual keyboard device.
                        if (GetDeviceName(rawDevice.hDevice).Contains("RDP_KBD"))
                            continue;
                    }

                    deviceList.Add(new RawDevice(rawDevice.hDevice, rawDevice.dwType));
                }
            }

            return deviceList.ToArray(); // Will never return a null reference.
        }
Exemple #28
0
        /// <summary>
        /// Populate the given tree-view control with our Raw Input Devices.
        /// </summary>
        /// <param name="treeView"></param>
        public static void PopulateDeviceList(TreeView treeView)
        {
            // Get our list of devices
            RAWINPUTDEVICELIST[] ridList = null;
            uint deviceCount             = 0;
            int  res = Win32.Win32RawInput.NativeMethods.GetRawInputDeviceList(ridList, ref deviceCount, (uint)Marshal.SizeOf(typeof(RAWINPUTDEVICELIST)));

            if (res == -1)
            {
                // Just give up then
                return;
            }

            ridList = new RAWINPUTDEVICELIST[deviceCount];
            res     = Win32.Win32RawInput.NativeMethods.GetRawInputDeviceList(ridList, ref deviceCount, (uint)Marshal.SizeOf(typeof(RAWINPUTDEVICELIST)));
            if (res != deviceCount)
            {
                // Just give up then
                return;
            }

            // For each our device add a node to our treeview
            foreach (RAWINPUTDEVICELIST device in ridList)
            {
                Device hidDevice;

                // Try create our HID device.
                try
                {
                    hidDevice = new Device(device.hDevice);
                }
                catch
                {
                    continue;
                }

                TreeNode node = null;
                if (hidDevice.Product != null && hidDevice.Product.Length > 1)
                {
                    // Add the devices with a proper name at the top
                    node = treeView.Nodes.Insert(0, hidDevice.Name, hidDevice.FriendlyName);
                }
                else
                {
                    // Add other once at the bottom
                    node = treeView.Nodes.Add(hidDevice.Name, hidDevice.FriendlyName);
                }

                // Each device root node keeps a reference to our HID device
                node.Tag = hidDevice;

                // Populate device properties
                node.Nodes.Add("Manufacturer: " + hidDevice.Manufacturer);
                node.Nodes.Add("Product ID: 0x" + hidDevice.ProductId.ToString("X4"));
                node.Nodes.Add("Vendor ID: 0x" + hidDevice.VendorId.ToString("X4"));
                node.Nodes.Add("Version: " + hidDevice.Version);
                node.Nodes.Add(hidDevice.Info.dwType.ToString());
                if (hidDevice.Info.dwType == RawInputDeviceType.RIM_TYPEHID)
                {
                    node.Nodes.Add("UsagePage / UsageCollection: 0x" + hidDevice.Info.hid.usUsagePage.ToString("X4") + " / 0x" + hidDevice.Info.hid.usUsage.ToString("X4"));
                }

                if (hidDevice.InputCapabilitiesDescription != null)
                {
                    node.Nodes.Add(hidDevice.InputCapabilitiesDescription);
                }

                // Add button count
                node.Nodes.Add("Button Count: " + hidDevice.ButtonCount);

                // Those can be joystick/gamepad axis
                if (hidDevice.InputValueCapabilities != null)
                {
                    foreach (HIDP_VALUE_CAPS caps in hidDevice.InputValueCapabilities)
                    {
                        string des = Djlastnight.Hid.Device.InputValueCapabilityDescription(caps);
                        if (des != null)
                        {
                            node.Nodes.Add(des);
                        }
                    }
                }

                node.Nodes.Add(hidDevice.Name);
            }
        }
Exemple #29
0
        /// <summary>
        /// Iterates through the list provided by GetRawInputDeviceList,
        /// counting keyboard devices and adding them to deviceList.
        /// </summary>
        /// <returns>The number of keyboard devices found.</returns>
        public int EnumerateDevices()
        {
            int  NumberOfDevices = 0;
            uint deviceCount     = 0;
            int  dwSize          = (Marshal.SizeOf(typeof(RAWINPUTDEVICELIST)));

            // Get the number of raw input devices in the list,
            // then allocate sufficient memory and get the entire list
            if (GetRawInputDeviceList(IntPtr.Zero, ref deviceCount, (uint)dwSize) == 0)
            {
                IntPtr pRawInputDeviceList = Marshal.AllocHGlobal((int)(dwSize * deviceCount));
                GetRawInputDeviceList(pRawInputDeviceList, ref deviceCount, (uint)dwSize);

                // Iterate through the list, discarding undesired items
                // and retrieving further information on keyboard devices
                for (int i = 0; i < deviceCount; i++)
                {
                    DeviceInfo dInfo;
                    string     deviceName;
                    uint       pcbSize = 0;

                    RAWINPUTDEVICELIST rid = (RAWINPUTDEVICELIST)Marshal.PtrToStructure(
                        new IntPtr((pRawInputDeviceList.ToInt32() + (dwSize * i))),
                        typeof(RAWINPUTDEVICELIST));

                    GetRawInputDeviceInfo(rid.hDevice, RIDI_DEVICENAME, IntPtr.Zero, ref pcbSize);

                    if (pcbSize > 0)
                    {
                        IntPtr pData = Marshal.AllocHGlobal((int)pcbSize);
                        GetRawInputDeviceInfo(rid.hDevice, RIDI_DEVICENAME, pData, ref pcbSize);
                        deviceName = (string)Marshal.PtrToStringAnsi(pData);

                        // Drop the "root" keyboard and mouse devices used for Terminal
                        // Services and the Remote Desktop
                        if (deviceName.ToUpper().Contains("ROOT"))
                        {
                            continue;
                        }

                        // If the device is identified in the list as a keyboard or
                        // HID device, create a DeviceInfo object to store information
                        // about it
                        if (rid.dwType == RIM_TYPEKEYBOARD || rid.dwType == RIM_TYPEHID)
                        {
                            dInfo = new DeviceInfo();

                            dInfo.deviceName   = (string)Marshal.PtrToStringAnsi(pData);
                            dInfo.deviceHandle = rid.hDevice;
                            dInfo.deviceType   = GetDeviceType(rid.dwType);

                            // Check the Registry to see whether this is actually a
                            // keyboard, and to retrieve a more friendly description.
                            bool   IsKeyboardDevice = false;
                            string DeviceDesc       = ReadReg(deviceName, ref IsKeyboardDevice);
                            dInfo.Name = DeviceDesc;

                            // If it is a keyboard and it isn't already in the list,
                            // add it to the deviceList hashtable and increase the
                            // NumberOfDevices count
                            if (!deviceList.Contains(rid.hDevice) && IsKeyboardDevice)
                            {
                                NumberOfDevices++;
                                deviceList.Add(rid.hDevice, dInfo);
                            }
                        }
                        Marshal.FreeHGlobal(pData);
                    }
                }


                Marshal.FreeHGlobal(pRawInputDeviceList);

                return(NumberOfDevices);
            }
            else
            {
                throw new ApplicationException("An error occurred while retrieving the list of devices.");
            }
        }
        /// <summary>Iterates through the list provided by GetRawInputDeviceList,
        /// adding eligible devices to deviceList.
        /// </summary>
        /// <param name="deviceFilter">device type filter - when present, only process messages from devices of this type</param>
        /// <returns>The number of keyboard devices found.</returns>
        private static void EnumerateDevices(DeviceType?deviceFilter, out Dictionary <IntPtr, DeviceInfo> deviceList)
        {
            deviceList = new Dictionary <IntPtr, DeviceInfo>();

            uint deviceCount = 0;

            // Get the number of raw input devices in the list,
            // then allocate sufficient memory and get the entire list
            int dwSize = (Marshal.SizeOf(typeof(RAWINPUTDEVICELIST)));

            if (GetRawInputDeviceList(IntPtr.Zero, ref deviceCount, (uint)dwSize) == 0)
            {
                IntPtr pRawInputDeviceList = Marshal.AllocHGlobal((int)(dwSize * deviceCount));
                GetRawInputDeviceList(pRawInputDeviceList, ref deviceCount, (uint)dwSize);

                // Iterate through the list, discarding undesired items
                // and retrieving further information on keyboard devices
                for (int i = 0; i < deviceCount; i++)
                {
                    RAWINPUTDEVICELIST rid = (RAWINPUTDEVICELIST)Marshal.PtrToStructure(
                        new IntPtr((pRawInputDeviceList.ToInt32() + (dwSize * i))),
                        typeof(RAWINPUTDEVICELIST));
                    uint pcbSize = 0;
                    GetRawInputDeviceInfo(rid.hDevice, RIDI_DEVICENAME, IntPtr.Zero, ref pcbSize);

                    if (pcbSize > 0)
                    {
                        IntPtr pData = Marshal.AllocHGlobal((int)pcbSize);
                        GetRawInputDeviceInfo(rid.hDevice, RIDI_DEVICENAME, pData, ref pcbSize);

                        string deviceDescriptor = (string)Marshal.PtrToStringAnsi(pData);

                        // Drop the "root" keyboard and mouse devices used for Terminal
                        // Services and the Remote Desktop
                        if (deviceDescriptor.ToUpper().Contains("ROOT"))
                        {
                            continue;
                        }

                        // If the device is identified in the list as a keyboard or
                        // HID device, create a DeviceInfo object to store information
                        // about it
                        if (rid.dwType == RIM_TYPEKEYBOARD || rid.dwType == RIM_TYPEHID)
                        {
                            DeviceInfo dInfo = new DeviceInfo();

                            dInfo.Handle     = rid.hDevice;
                            dInfo.Descriptor = deviceDescriptor;
                            dInfo.DType      = GetDeviceType(rid.dwType, deviceDescriptor);

                            // Check the Registry to see whether this is actually a
                            // keyboard, and to retrieve a more friendly description.
                            string deviceDesc;
                            string deviceClass;
                            bool   isKeyboardDevice;

                            ReadReg(deviceDescriptor, out deviceDesc, out deviceClass, out isKeyboardDevice);
                            dInfo.Name = deviceDesc;

                            // If it is a keyboard and it isn't already in the list
                            // and matches the device type filter, if provided, then
                            // add it to the deviceList.
                            if (isKeyboardDevice && !deviceList.ContainsKey(rid.hDevice))
                            {
                                if (deviceFilter == null || deviceFilter.Value == dInfo.DType)
                                {
                                    deviceList.Add(dInfo.Handle, dInfo);
                                }
                            }
                        }
                        Marshal.FreeHGlobal(pData);
                    }
                }


                Marshal.FreeHGlobal(pRawInputDeviceList);
            }
            else
            {
                throw new ApplicationException("An error occurred while retrieving the list of devices.");
            }
        }
Exemple #31
0
        public static List <DeviceDetails> EnumerateDevices()
        {
            uint deviceCount = 0;
            int  dwSize      = Marshal.SizeOf(typeof(RAWINPUTDEVICELIST));

            // Get the number of raw input devices in the list,
            // then allocate sufficient memory and get the entire list
            if (GetRawInputDeviceList(IntPtr.Zero, ref deviceCount, (uint)dwSize) == 0)
            {
                IntPtr pRawInputDeviceList = Marshal.AllocHGlobal((int)(dwSize * deviceCount));
                GetRawInputDeviceList(pRawInputDeviceList, ref deviceCount, (uint)dwSize);

                List <DeviceDetails> devices = new List <DeviceDetails>((int)deviceCount);

                // Iterate through the list, discarding undesired items
                // and retrieving further information on keyboard devices
                for (int i = 0; i < deviceCount; i++)
                {
                    uint pcbSize = 0;

                    IntPtr location;
                    int    offset = dwSize * i;

                    if (IntPtr.Size == 4)
                    {
                        location = new IntPtr(pRawInputDeviceList.ToInt32() + offset);
                    }
                    else
                    {
                        location = new IntPtr(pRawInputDeviceList.ToInt64() + offset);
                    }

                    RAWINPUTDEVICELIST rid = (RAWINPUTDEVICELIST)Marshal.PtrToStructure(location, typeof(RAWINPUTDEVICELIST));

                    GetRawInputDeviceInfo(rid.hDevice, RIDI_DEVICENAME, IntPtr.Zero, ref pcbSize);

                    if (pcbSize > 0)
                    {
                        IntPtr pData = Marshal.AllocHGlobal((int)pcbSize);
                        GetRawInputDeviceInfo(rid.hDevice, RIDI_DEVICENAME, pData, ref pcbSize);
                        string deviceName = Marshal.PtrToStringAnsi(pData);

                        // Drop the "root" keyboard and mouse devices used for Terminal Services and the Remote Desktop
                        if (deviceName.ToUpperInvariant().Contains("ROOT"))
                        {
                            continue;
                        }

                        // If the device is identified in the list as a keyboard or
                        // HID device, create a DeviceInfo object to store information
                        // about it

                        // Get Detailed Info ...
                        uint       size = (uint)Marshal.SizeOf(typeof(DeviceInfo));
                        DeviceInfo di   = new DeviceInfo();
                        di.Size = Marshal.SizeOf(typeof(DeviceInfo));
                        GetRawInputDeviceInfo(rid.hDevice, RIDI_DEVICEINFO, ref di, ref size);

                        di      = new DeviceInfo();
                        di.Size = Marshal.SizeOf(typeof(DeviceInfo));
                        GetRawInputDeviceInfo(rid.hDevice, RIDI_DEVICEINFO, ref di, ref size);

                        DeviceDetails details = new DeviceDetails();
                        //details.Name = deviceName;
                        details.ID = deviceName;

                        switch (di.Type)
                        {
                        case RawInputType.HID:
                        {
                            string vidAndPid = String.Format("Vid_{0:x4}&Pid_{1:x4}", di.HIDInfo.VendorID, di.HIDInfo.ProductID);
                            details.Name = String.Format("HID: {0}", GetFriendlyName(vidAndPid));
                            //details.ID = GetDeviceDesc(deviceName);

                            details.UsagePage = di.HIDInfo.UsagePage;
                            details.Usage     = di.HIDInfo.Usage;

                            devices.Add(details);
                            break;
                        }

                        case RawInputType.Keyboard:
                        {
                            details.Name = "HID Keyboard";
                            //details.ID = String.Format("{0}-{1}", di.KeyboardInfo.Type, di.KeyboardInfo.SubType);

                            details.UsagePage = 0x01;
                            details.Usage     = 0x06;

                            devices.Add(details);
                            break;
                        }

                        case RawInputType.Mouse:
                        {
                            details.Name = "HID Mouse";

                            details.UsagePage = 0x01;
                            details.Usage     = 0x02;

                            devices.Add(details);
                            break;
                        }
                        }

                        Marshal.FreeHGlobal(pData);
                    }
                }

                Marshal.FreeHGlobal(pRawInputDeviceList);

                return(devices);
            }
            else
            {
                throw new InvalidOperationException("An error occurred while retrieving the list of devices");
            }
        }
Exemple #32
0
        public void LoadDevices()
        {
            lock (_lockObj)
            {
                Devices.Clear();
                var currentKeyboard = 1;

                RawDevice nullKeyboard = new RawDevice()
                {
                    Handle = IntPtr.Zero,
                    HWID   = "NULL",
                    Id     = currentKeyboard,
                    Name   = "Not identified keypress",
                    Type   = RawInputDeviceType.KEYBOARD
                };

                Devices.Add(nullKeyboard.Handle, nullKeyboard);

                var structSize = Marshal.SizeOf(typeof(RAWINPUTDEVICELIST));

                var bufferCount = 0u;

                if (GetRawInputDeviceList(null, ref bufferCount, (uint)structSize) == 0)
                {
                    RAWINPUTDEVICELIST[] rawDeviceList = new RAWINPUTDEVICELIST[bufferCount];
                    GetRawInputDeviceList(rawDeviceList, ref bufferCount, (uint)structSize);

                    foreach (var device in rawDeviceList)
                    {
                        if (device.Type == RawInputDeviceType.KEYBOARD || device.Type == RawInputDeviceType.HID)
                        {
                            currentKeyboard++;
                            uint size = 0;
                            GetRawInputDeviceInfo(device.hDevice, (uint)RawInputDeviceInfo.DeviceName, IntPtr.Zero, ref size);
                            var data = Marshal.AllocHGlobal((int)size);
                            GetRawInputDeviceInfo(device.hDevice, (uint)RawInputDeviceInfo.DeviceName, data, ref size);

                            var HWID = Marshal.PtrToStringAnsi(data);

                            RawDevice rawDevice = new RawDevice()
                            {
                                HWID   = HWID,
                                Handle = device.hDevice,
                                Id     = currentKeyboard,
                                Type   = device.Type,
                                Name   = RawInputHelper.GetDeviceName(HWID)
                            };

                            if (!Devices.ContainsKey(device.hDevice))
                            {
                                Devices.Add(device.hDevice, rawDevice);
                            }

                            Marshal.FreeHGlobal(data);
                        }
                    }
                    return;
                }
            }
            throw new Exception("Error: " + Marshal.GetLastWin32Error());
        }
Exemple #33
0
        /// <summary>
        /// Iterates through the list provided by GetRawInputDeviceList,
        /// counting keyboard devices and adding them to deviceList.
        /// </summary>
        /// <returns>The number of keyboard devices found.</returns>
        public int EnumerateDevices()
        {
            deviceList.Clear();
            int  NumberOfDevices = 0;
            uint deviceCount     = 0;
            int  dwSize          = (Marshal.SizeOf(typeof(RAWINPUTDEVICELIST)));

            // Get the number of raw input devices in the list,
            // then allocate sufficient memory and get the entire list
            if (GetRawInputDeviceList(IntPtr.Zero, ref deviceCount, (uint)dwSize) == 0)
            {
                IntPtr pRawInputDeviceList = Marshal.AllocHGlobal((int)(dwSize * deviceCount));
                GetRawInputDeviceList(pRawInputDeviceList, ref deviceCount, (uint)dwSize);

                // Iterate through the list, discarding undesired items
                // and retrieving further information on keyboard devices
                for (int i = 0; i < deviceCount; i++)
                {
                    DeviceInfo dInfo;
                    string     deviceName;
                    uint       pcbSize = 0;

                    RAWINPUTDEVICELIST rid = (RAWINPUTDEVICELIST)Marshal.PtrToStructure(
                        new IntPtr((pRawInputDeviceList.ToInt32() + (dwSize * i))),
                        typeof(RAWINPUTDEVICELIST));

                    GetRawInputDeviceInfo(rid.hDevice, RIDI_DEVICENAME, IntPtr.Zero, ref pcbSize);

                    if (pcbSize > 0)
                    {
                        IntPtr pData = Marshal.AllocHGlobal((int)pcbSize);
                        GetRawInputDeviceInfo(rid.hDevice, RIDI_DEVICENAME, pData, ref pcbSize);
                        deviceName = (string)Marshal.PtrToStringAnsi(pData);

                        // Drop the "root" keyboard and mouse devices used for Terminal
                        // Services and the Remote Desktop
                        if (deviceName.ToUpper().Contains("ROOT"))
                        {
                            continue;
                        }

                        // add mouse device and retrive VID/PID for future reference
                        if (rid.dwType == RIM_TYPEMOUSE)
                        {
                            dInfo = new DeviceInfo();

                            dInfo.deviceName   = (string)Marshal.PtrToStringAnsi(pData);
                            dInfo.deviceHandle = rid.hDevice;
                            dInfo.deviceType   = GetDeviceType(rid.dwType);
                            string DeviceDesc = ReadReg(deviceName);
                            dInfo.Name = DeviceDesc;

                            var    exp   = new Regex(@"VID_(?<Vid>[0-9A-F]+)&PID_(?<Pid>[0-9A-F]+)");
                            var    match = exp.Match(dInfo.deviceName);
                            String id    = match.Groups["Vid"].ToString() + "_" + match.Groups["Pid"].ToString();
                            dInfo.source = id;

                            Debug.WriteLine("{0},{1},{2}", dInfo.deviceName, id, dInfo.deviceHandle);

                            if (!deviceList.Contains(rid.hDevice))
                            {
                                NumberOfDevices++;
                                deviceList.Add(rid.hDevice, dInfo);
                            }
                        }

                        Marshal.FreeHGlobal(pData);
                    }
                }
                Marshal.FreeHGlobal(pRawInputDeviceList);

                return(NumberOfDevices);
            }
            else
            {
                throw new ApplicationException("An error occurred while retrieving the list of devices.");
            }
        }