Exemple #1
0
        /// <summary>
        /// Get HID attributes.
        /// </summary>
        /// <param name="hidHandle"> HID handle retrieved with CreateFile </param>
        /// <param name="deviceAttributes"> HID attributes structure </param>
        /// <returns> true on success </returns>

        internal Boolean GetAttributes(SafeFileHandle hidHandle, ref NativeMethods.HIDD_ATTRIBUTES deviceAttributes)
        {
            Boolean success;

            try
            {
                //  ***
                //  API function:
                //  HidD_GetAttributes

                //  Purpose:
                //  Retrieves a HIDD_ATTRIBUTES structure containing the Vendor ID,
                //  Product ID, and Product Version Number for a device.

                //  Accepts:
                //  A handle returned by CreateFile.
                //  A pointer to receive a HIDD_ATTRIBUTES structure.

                //  Returns:
                //  True on success, False on failure.
                //  ***

                success = NativeMethods.HidD_GetAttributes(hidHandle, ref deviceAttributes);
            }

            catch (Exception ex)
            {
                DisplayException(ModuleName, ex);
                throw;
            }
            return(success);
        }
Exemple #2
0
        ///  <summary>
        ///  Get HID attributes.
        ///  </summary>
        ///
        ///  <param name="hidHandle">HID handle retrieved with CreateFile.</param>
        ///  <param name="deviceAttributes">HID attributes structure.</param>
        ///
        ///  <returns>True on success. False on failure.</returns>

        internal Boolean GetAttributes(SafeFileHandle hidHandle, ref NativeMethods.HIDD_ATTRIBUTES deviceAttributes)
        {
            Boolean success = false;

            traceSource.TraceEvent(TraceEventType.Verbose, 1, "GetAttributes");

            try
            {
                //  ***
                //  API function:
                //  HidD_GetAttributes

                //  Purpose:
                //  Retrieves a HIDD_ATTRIBUTES structure containing the Vendor ID,
                //  Product ID, and Product Version Number for a device.

                //  Accepts:
                //  A handle returned by CreateFile.
                //  A pointer to receive a HIDD_ATTRIBUTES structure.

                //  Returns:
                //  True on success, False on failure.
                //  ***

                success = NativeMethods.HidD_GetAttributes(hidHandle, ref deviceAttributes);
            }
            catch (Exception ex)
            {
                DisplayException(MethodBase.GetCurrentMethod().Name, ex, ShowMsgBoxOnException);
            }

            return(success);
        }
Exemple #3
0
        internal HidDeviceAttributes(NativeMethods.HIDD_ATTRIBUTES attributes)
        {
            VendorId  = attributes.VendorID;
            ProductId = attributes.ProductID;
            Version   = attributes.VersionNumber;

            VendorHexId  = "0x" + attributes.VendorID.ToString("X4");
            ProductHexId = "0x" + attributes.ProductID.ToString("X4");
        }
        internal static WinHidDevice TryCreate(string path, string id)
        {
            var d = new WinHidDevice()
            {
                _path = path, _id = id
            };

            return(d.TryOpenToGetInfo(handle =>
            {
                NativeMethods.HIDD_ATTRIBUTES attributes = new NativeMethods.HIDD_ATTRIBUTES();
                attributes.Size = Marshal.SizeOf(attributes);
                if (!NativeMethods.HidD_GetAttributes(handle, ref attributes))
                {
                    return false;
                }

                // Get VID, PID, version.
                d._pid = attributes.ProductID;
                d._vid = attributes.VendorID;
                d._version = attributes.VersionNumber;
                return true;
            }) ? d : null);
        }
Exemple #5
0
        IList <string> FindHidDevicePathList()
        {
            // TODO: MUSTDO: fix for multiple device connection
            // Use UpdateDevicePathIfDevicePathIsNullOrEmpty() in normal use case.
            // Because if you always use this method in every HID access, CPU usage increase from <1% to 5%-10%.
            // And the UpdateDevicePath() occupies 87.8% of all application CPU times.

            // TODO: MUSTDO: GetInstalledDeviceDevicePathListByInterfaceClassGuid duplicated.  This is not deleted because this code may be faster since it does not get Capability and this was correct.
            // TODO: MUSTDO: Like GetInstalledDeviceDevicePathListByInterfaceClassGuid, it should detect when the app starts and device connection status changes.
            var ret = new List <string>();

            // TODO: MUSTDO: ProductIdは0xA001に統一される。
            foreach (var targetHidGuid in TargetHidGuidList)
            {
                int index = 0;
                // copy
                Guid hidGuid = targetHidGuid;
                NativeMethods.SP_DEVICE_INTERFACE_DATA deviceInterfaceData = new NativeMethods.SP_DEVICE_INTERFACE_DATA();
                deviceInterfaceData.cbSize = (uint)Marshal.SizeOf(deviceInterfaceData);

                // Enumerate devices.
                var hDevInfo = NativeMethods.SetupDiGetClassDevs(ref hidGuid, IntPtr.Zero, IntPtr.Zero, NativeMethods.DIGCF_DEVICEINTERFACE | NativeMethods.DIGCF_PRESENT);

                while (NativeMethods.SetupDiEnumDeviceInterfaces(hDevInfo, IntPtr.Zero, ref hidGuid, index, ref deviceInterfaceData))
                {
                    UInt32 size;
                    NativeMethods.SetupDiGetDeviceInterfaceDetail(hDevInfo, ref deviceInterfaceData, IntPtr.Zero, 0, out size, IntPtr.Zero);
                    NativeMethods.SP_DEVICE_INTERFACE_DETAIL_DATA deviceInterfaceDetailData = new NativeMethods.SP_DEVICE_INTERFACE_DETAIL_DATA();
                    deviceInterfaceDetailData.cbSize = (uint)(IntPtr.Size == 8 ? 8 : 5);
                    // Get detail information
                    NativeMethods.SetupDiGetDeviceInterfaceDetail(hDevInfo, ref deviceInterfaceData, ref deviceInterfaceDetailData, size, out size, IntPtr.Zero);
                    //Debug.WriteLine(index + " " + deviceInterfaceDetailData.DevicePath + " " + Marshal.GetLastWin32Error());

                    // open a read/write handle to our device using the DevicePath returned
                    SafeFileHandle handle = null;
                    try
                    {
                        handle = NativeMethods.CreateFile(deviceInterfaceDetailData.DevicePath, 0, FileShare.ReadWrite, IntPtr.Zero, FileMode.Open, NativeMethods.EFileAttributes.Overlapped, IntPtr.Zero);
                        // create an attributes struct and initialize the size
                        NativeMethods.HIDD_ATTRIBUTES attrib = new NativeMethods.HIDD_ATTRIBUTES();
                        attrib.Size = (uint)Marshal.SizeOf(attrib);
                        // get the attributes of the current device
                        if (NativeMethods.HidD_GetAttributes(handle.DangerousGetHandle(), ref attrib))
                        {
                            //Debug.WriteLine(deviceInterfaceDetailData.DevicePath + " " + attrib.VendorID +" / " +attrib.ProductID);

                            // if the vendor and product IDs match up
                            if (attrib.VendorID != VendorId)
                            {
                                continue;
                            }
                            if (attrib.ProductID != ProductId)
                            {
                                continue;
                            }
                            var lowered = deviceInterfaceDetailData.DevicePath.ToLower(System.Globalization.CultureInfo.InvariantCulture);
                            if (lowered.Contains(HidEgsGestureInterfaceTag) == false)
                            {
                                continue;
                            }
                            if (lowered.Contains(HidEgsGestureInterface_VendorSpecificCollectionTag) == false)
                            {
                                continue;
                            }
                            ret.Add(deviceInterfaceDetailData.DevicePath);
                        }
                    }
                    finally
                    {
                        handle.Close();
                        index++;
                    }
                }
            }
            return(ret);
        }
Exemple #6
0
        internal bool CheckDeviceIsConnected(string checkingDeviceDevicePath)
        {
            //  ***
            //  API function:
            //  CreateFile

            //  Purpose:
            //  Retrieves a handle to a device.

            //  Accepts:
            //  A device path name returned by SetupDiGetDeviceInterfaceDetail
            //  The type of access requested (read/write).
            //  FILE_SHARE attributes to allow other processes to access the device while this handle is open.
            //  A Security structure or IntPtr.Zero.
            //  A creation disposition value. Use OPEN_EXISTING for devices.
            //  Flags and attributes for files. Not used for devices.
            //  Handle to a template file. Not used.

            //  Returns: a handle without read or write access.
            //  This enables obtaining information about all HIDs, even system
            //  keyboards and mice.
            //  Separate handles are used for reading and writing.
            //  ***

            // Open the handle without read/write access to enable getting information about any HID, even system keyboards and mice.
            const int isGettingOnlyConnectionState = 0;

            using (var tempHandle = NativeMethods.CreateFile(checkingDeviceDevicePath, isGettingOnlyConnectionState, FileShare.ReadWrite, IntPtr.Zero, FileMode.Open, NativeMethods.EFileAttributes.Device, IntPtr.Zero))
            {
                Debug.WriteLine(NativeMethods.GetResultOfApiCall("CreateFile") + Environment.NewLine + "  Returned handle: " + tempHandle.ToString());

                if (tempHandle.IsInvalid)
                {
                    return(false);
                }

                //  The returned handle is valid,
                //  so find out if this is the device we're looking for.
                //  Set the Size property of DeviceAttributes to the number of bytes in the structure.
                NativeMethods.HIDD_ATTRIBUTES DeviceAttributes = new NativeMethods.HIDD_ATTRIBUTES();
                DeviceAttributes.Size = (uint)Marshal.SizeOf(DeviceAttributes);
                var hr = NativeMethods.HidD_GetAttributes(tempHandle, ref DeviceAttributes);
                if (hr == false)
                {
                    //  There was a problem in retrieving the information.
                    Debug.WriteLine("Error in filling HIDD_ATTRIBUTES structure.");
                    return(false);
                }

#if false
                if (false)
                {
                    Debug.WriteLine("[HIDD_ATTRIBUTES structure filled without error.]");
                    Debug.WriteLine("        Structure size: " + DeviceAttributes.Size);
                    Debug.WriteLine("        Vendor ID: " + Convert.ToString(DeviceAttributes.VendorID, 16));
                    Debug.WriteLine("        Product ID: " + Convert.ToString(DeviceAttributes.ProductID, 16));
                    Debug.WriteLine("        Version Number: " + Convert.ToString(DeviceAttributes.VersionNumber, 16));
                    Debug.WriteLine("");
                }
#endif

                //  Find out if the device matches the one we're looking for.
                if (DeviceAttributes.VendorID == VendorId)
                {
                    return(true);
                }
                Debugger.Break();
                return(false);
            }
        }