Exemple #1
0
 public static extern bool SetupDiGetDeviceInterfaceDetail(
     IntPtr lpDeviceInfoSet,
     ref DeviceInterfaceData oInterfaceData,
     IntPtr lpDeviceInterfaceDetailData,         //To get the nRequiredSize
     uint nDeviceInterfaceDetailDataSize,
     ref uint nRequiredSize,
     ref DevinfoData deviceInfoData);
        public static HidDevice FindDevice(int nVid, int nPid, Type oType)
        {
            string strPath   = string.Empty;
            string strSearch = string.Format("vid_{0:x4}&pid_{1:x4}", nVid, nPid);
            Guid   gHid      = HIDGuid;
            IntPtr hInfoSet  = SetupDiGetClassDevs(ref gHid, null, IntPtr.Zero, DIGCF_DEVICEINTERFACE | DIGCF_PRESENT);

            try
            {
                DeviceInterfaceData oInterface = new DeviceInterfaceData();
                oInterface.Size = Marshal.SizeOf(oInterface);
                int nIndex = 0;
                while (SetupDiEnumDeviceInterfaces(hInfoSet, 0, ref gHid, (uint)nIndex, ref oInterface))
                {
                    string strDevicePath = GetDevicePath(hInfoSet, ref oInterface);
                    if (strDevicePath.IndexOf(strSearch) >= 0)
                    {
                        HidDevice oNewDevice = (HidDevice)Activator.CreateInstance(oType);
                        oNewDevice.Initialise(strDevicePath);
                        return(oNewDevice);
                    }
                    nIndex++;
                }
            }
            catch (Exception ex)
            {
                throw HidDeviceException.GenerateError(ex.ToString());
            }
            finally
            {
                SetupDiDestroyDeviceInfoList(hInfoSet);
            }
            // No device found.
            return(null);
        }
Exemple #3
0
 public static extern bool SetupDiGetDeviceInterfaceDetail(
     IntPtr lpDeviceInfoSet,
     ref DeviceInterfaceData oInterfaceData,
     ref DeviceInterfaceDetailData oDetailData,  //We have the size -> send struct
     uint nDeviceInterfaceDetailDataSize,
     ref uint nRequiredSize,
     ref DevinfoData deviceInfoData);
Exemple #4
0
        public static string[] Find(int nVid, int nPid)
        {
            Guid          guid;
            List <string> list = new List <string>();
            string        str  = string.Format("vid_{0:x4}&pid_{1:x4}", nVid, nPid);

            HidD_GetHidGuid(out guid);
            IntPtr lpDeviceInfoSet = SetupDiGetClassDevs(ref guid, null, IntPtr.Zero, 0x12);

            try
            {
                DeviceInterfaceData structure = new DeviceInterfaceData();
                structure.Size = Marshal.SizeOf(structure);
                for (int i = 0; SetupDiEnumDeviceInterfaces(lpDeviceInfoSet, 0, ref guid, (uint)i, ref structure); i++)
                {
                    string devicePath = GetDevicePath(lpDeviceInfoSet, ref structure);
                    if (devicePath.IndexOf(str) >= 0)
                    {
                        list.Add(devicePath);
                    }
                }
            }
            finally
            {
                SetupDiDestroyDeviceInfoList(lpDeviceInfoSet);
            }
            return(list.ToArray());
        }
Exemple #5
0
        /// <summary>
        /// Helper method to return the device path given a DeviceInterfaceData structure and an InfoSet handle.
        /// Used in 'FindDevice' so check that method out to see how to get an InfoSet handle and a DeviceInterfaceData.
        /// </summary>
        /// <param name="hInfoSet">Handle to the InfoSet</param>
        /// <param name="oInterface">DeviceInterfaceData structure</param>
        /// <returns>The device path or null if there was some problem</returns>
        private static string GetDevicePath(IntPtr hInfoSet, ref DeviceInterfaceData oInterface)
        {
            Int32  nRequiredSize    = 0;
            IntPtr detailDataBuffer = IntPtr.Zero;

            // Get the device interface details
            if (!SetupDiGetDeviceInterfaceDetail(hInfoSet, ref oInterface, IntPtr.Zero, 0, ref nRequiredSize, IntPtr.Zero))
            {
                //DeviceInterfaceDetailData oDetail = new DeviceInterfaceDetailData();
                //oDetail.Size = (IntPtr.Size == 4) ? (4 + Marshal.SystemDefaultCharSize) : 8;
                detailDataBuffer = Marshal.AllocHGlobal(nRequiredSize);
                Marshal.WriteInt32(detailDataBuffer, (IntPtr.Size == 4)?(4 + Marshal.SystemDefaultCharSize):8);

                //DeviceInterfaceDetailData oDetail = new DeviceInterfaceDetailData();
                //oDetail.Size = 5;	// hardcoded to 5! Sorry, but this works and trying more future proof versions by setting the size to the struct sizeof failed miserably. If you manage to sort it, mail me! Thx
                if (SetupDiGetDeviceInterfaceDetail(hInfoSet, ref oInterface, detailDataBuffer, nRequiredSize, ref nRequiredSize, IntPtr.Zero))
                {
                    String devicePathName  = "";
                    var    pDevicePathName = new IntPtr(detailDataBuffer.ToInt64() + 4);
                    devicePathName = Marshal.PtrToStringAuto(pDevicePathName);
                    Marshal.FreeHGlobal(detailDataBuffer);
                    return(devicePathName);
                }
            }
            return(null);
        }
Exemple #6
0
        /// <summary>
        /// Finds a device given its PID and VID
        /// </summary>
        /// <param name="nVid">Vendor id for device (VID)</param>
        /// <param name="nPid">Product id for device (PID)</param>
        /// <param name="oType">Type of device class to create</param>
        /// <returns>A new device class of the given type or null</returns>
        public static HIDDevice FindDevice(int nVid, int nPid, Type oType)
        {
            var searchPath = GetSearchPath(nVid, nPid); // first, build the path search string
            Guid gHid;
            HidD_GetHidGuid(out gHid);	// next, get the GUID from Windows that it uses to represent the HID USB interface
            var hInfoSet = SetupDiGetClassDevs(ref gHid, null, IntPtr.Zero, DIGCF_DEVICEINTERFACE | DIGCF_PRESENT);	// this gets a list of all HID devices currently connected to the computer (InfoSet)
            try
            {
                var oInterface = new DeviceInterfaceData();	// build up a device interface data block
                oInterface.Size = Marshal.SizeOf(oInterface);
                // Now iterate through the InfoSet memory block assigned within Windows in the call to SetupDiGetClassDevs
                // to get device details for each device connected
                for (var i = 0; SetupDiEnumDeviceInterfaces(hInfoSet, 0, ref gHid, (uint)i, ref oInterface); i++)	// this gets the device interface information for a device at index 'i' in the memory block
                {
                    var strDevicePath = GetDevicePath(hInfoSet, ref oInterface);	// get the device path (see helper method 'GetDevicePath')
                    if (strDevicePath.IndexOf(searchPath) < 0)
                        continue;

                    var oNewDevice = (HIDDevice)Activator.CreateInstance(oType);	// create an instance of the class for this device
                    oNewDevice.Initialise(strDevicePath);	// initialise it with the device path
                    return oNewDevice;	// and return it
                }
            }
            finally
            {
                // Before we go, we have to free up the InfoSet memory reserved by SetupDiGetClassDevs
                SetupDiDestroyDeviceInfoList(hInfoSet);
            }
            return null;	// oops, didn't find our device
        }
 /// <summary>
 /// Finds a device given its PID and VID
 /// </summary>
 /// <param name="VendorID">Vendor id for device (VID)</param>
 /// <param name="ProductID">Product id for device (PID)</param>
 /// <param name="oType">Type of device class to create</param>
 /// <returns>A new device class of the given type or null</returns>
 public static HIDDevice FindDevice(int VendorID, int ProductID, Type oType)
 {
     string strPath = string.Empty;
     string strSearch = string.Format("vid_{0:x4}&pid_{1:x4}", VendorID, ProductID); // first, build the path search string
     Guid gHid;
     HidD_GetHidGuid(out gHid);	// next, get the GUID from Windows that it uses to represent the HID USB interface
     IntPtr hInfoSet = SetupDiGetClassDevs(ref gHid, null, IntPtr.Zero, DIGCF_DEVICEINTERFACE | DIGCF_PRESENT);	// this gets a list of all HID devices currently connected to the computer (InfoSet)
     try
     {
         DeviceInterfaceData oInterface = new DeviceInterfaceData();	// build up a device interface data block
         oInterface.Size = Marshal.SizeOf(oInterface);
         // Now iterate through the InfoSet memory block assigned within Windows in the call to SetupDiGetClassDevs
         // to get device details for each device connected
         int nIndex = 0;
         while (SetupDiEnumDeviceInterfaces(hInfoSet, 0, ref gHid, (uint)nIndex, ref oInterface))	// this gets the device interface information for a device at index 'nIndex' in the memory block
         {
             string strDevicePath = GetDevicePath(hInfoSet, ref oInterface);	// get the device path (see helper method 'GetDevicePath')
             if (strDevicePath.IndexOf(strSearch) >= 0)	// do a string search, if we find the VID/PID string then we found our device!
             {
                 HIDDevice oNewDevice = (HIDDevice)Activator.CreateInstance(oType);	// create an instance of the class for this device
                 oNewDevice.Initialize(strDevicePath);	// initialise it with the device path
                 return oNewDevice;	// and return it
             }
             nIndex++;	// if we get here, we didn't find our device. So move on to the next one.
         }
     }
     finally
     {
         // Before we go, we have to free up the InfoSet memory reserved by SetupDiGetClassDevs
         SetupDiDestroyDeviceInfoList(hInfoSet);
     }
     return null;	// oops, didn't find our device
 }
Exemple #8
0
 private static extern bool SetupDiGetDeviceInterfaceDetail(
     IntPtr handle,
     ref DeviceInterfaceData deviceInterfaceData,
     IntPtr unused1,
     int unused2,
     ref uint requiredSize,
     IntPtr unused3);
Exemple #9
0
 private static extern bool SetupDiGetDeviceInterfaceDetail(
     IntPtr handle,
     ref DeviceInterfaceData deviceInterfaceData,
     ref DeviceInterfaceDetailData deviceInterfaceDetailData,
     uint detailSize,
     IntPtr unused1,
     IntPtr unused2);
Exemple #10
0
        /// <summary>
        /// Finds a device given its PID and VID
        /// </summary>
        /// <param name="nVid">Vendor id for device (VID)</param>
        /// <param name="nPid">Product id for device (PID)</param>
        /// <param name="oType">Type of device class to create</param>
        /// <returns>A new device class of the given type or null</returns>
        public static HIDDevice FindDevice(int nVid, int nPid, Type oType)
        {
            var  searchPath = GetSearchPath(nVid, nPid); // first, build the path search string
            Guid gHid;

            HidD_GetHidGuid(out gHid);                                                                              // next, get the GUID from Windows that it uses to represent the HID USB interface
            var hInfoSet = SetupDiGetClassDevs(ref gHid, null, IntPtr.Zero, DIGCF_DEVICEINTERFACE | DIGCF_PRESENT); // this gets a list of all HID devices currently connected to the computer (InfoSet)

            try
            {
                var oInterface = new DeviceInterfaceData();     // build up a device interface data block
                oInterface.Size = Marshal.SizeOf(oInterface);
                // Now iterate through the InfoSet memory block assigned within Windows in the call to SetupDiGetClassDevs
                // to get device details for each device connected
                for (var i = 0; SetupDiEnumDeviceInterfaces(hInfoSet, 0, ref gHid, (uint)i, ref oInterface); i++) // this gets the device interface information for a device at index 'i' in the memory block
                {
                    var strDevicePath = GetDevicePath(hInfoSet, ref oInterface);                                  // get the device path (see helper method 'GetDevicePath')
                    if (strDevicePath.IndexOf(searchPath) < 0)
                    {
                        continue;
                    }

                    var oNewDevice = (HIDDevice)Activator.CreateInstance(oType); // create an instance of the class for this device
                    oNewDevice.Initialise(strDevicePath);                        // initialise it with the device path
                    return(oNewDevice);                                          // and return it
                }
            }
            finally
            {
                // Before we go, we have to free up the InfoSet memory reserved by SetupDiGetClassDevs
                SetupDiDestroyDeviceInfoList(hInfoSet);
            }
            return(null);        // oops, didn't find our device
        }
Exemple #11
0
        /// <summary>
        /// Helper method to return the device path given a DeviceInterfaceData structure and an InfoSet handle.
        /// Used in 'FindDevice' so check that method out to see how to get an InfoSet handle and a DeviceInterfaceData.
        /// </summary>
        /// <param name="hInfoSet">Handle to the InfoSet</param>
        /// <param name="oInterface">DeviceInterfaceData structure</param>
        /// <returns>The device path or null if there was some problem</returns>
        private static string GetDevicePath(IntPtr hInfoSet, ref DeviceInterfaceData oInterface)
        {
            uint nRequiredSize = 0;

            // Get the device interface details
            if (!SetupDiGetDeviceInterfaceDetail(hInfoSet, ref oInterface, IntPtr.Zero, 0, ref nRequiredSize, IntPtr.Zero))
            {
                DeviceInterfaceDetailData oDetail = new DeviceInterfaceDetailData();
                if (Marshal.SizeOf(typeof(IntPtr)) == 8)
                {
                    oDetail.Size = 8; // For 64 bit.
                }
                else
                {
                    oDetail.Size = 5; // hardcoded to 5!  (I think this correctly handles 32 bit systems, but not yet tested)
                }

                if (SetupDiGetDeviceInterfaceDetail(hInfoSet, ref oInterface, ref oDetail, nRequiredSize, ref nRequiredSize, IntPtr.Zero))
                {
                    return(oDetail.DevicePath);
                }
            }

            return(null);
        }
Exemple #12
0
        public static HIDDevice FindDevice(int nVid, int nPid, Type oType)
        {
            string value   = string.Format("vid_{0:x4}&pid_{1:x4}", nVid, nPid);
            Guid   hIDGuid = Win32Usb.HIDGuid;
            IntPtr intPtr  = Win32Usb.SetupDiGetClassDevs(ref hIDGuid, null, IntPtr.Zero, 18u);

            try
            {
                DeviceInterfaceData deviceInterfaceData = default(DeviceInterfaceData);
                deviceInterfaceData.Size = Marshal.SizeOf(deviceInterfaceData);
                int num = 0;
                while (Win32Usb.SetupDiEnumDeviceInterfaces(intPtr, 0u, ref hIDGuid, (uint)num, ref deviceInterfaceData))
                {
                    string text = HIDDevice.smethod_0(intPtr, ref deviceInterfaceData);
                    if (text.IndexOf(value) < 0)
                    {
                        num++;
                        continue;
                    }
                    HIDDevice hIDDevice = (HIDDevice)Activator.CreateInstance(oType);
                    hIDDevice.method_0(text);
                    return(hIDDevice);
                }
            }
            catch (Exception ex)
            {
                throw GException0.GenerateError(ex.ToString());
            }
            finally
            {
                Marshal.GetLastWin32Error();
                Win32Usb.SetupDiDestroyDeviceInfoList(intPtr);
            }
            return(null);
        }
 public static HidDevice FindDevice(int nVid, int nPid, Type oType)
 {
     string strPath = string.Empty;
     string strSearch = string.Format("vid_{0:x4}&pid_{1:x4}", nVid, nPid);
     Guid gHid = HIDGuid;
     IntPtr hInfoSet = SetupDiGetClassDevs(ref gHid, null, IntPtr.Zero, DIGCF_DEVICEINTERFACE | DIGCF_PRESENT);
     try
     {
         DeviceInterfaceData oInterface = new DeviceInterfaceData();
         oInterface.Size = Marshal.SizeOf(oInterface);
         int nIndex = 0;
         while (SetupDiEnumDeviceInterfaces(hInfoSet, 0, ref gHid, (uint)nIndex, ref oInterface))
         {
             string strDevicePath = GetDevicePath(hInfoSet, ref oInterface);
             if (strDevicePath.IndexOf(strSearch) >= 0)
             {
                 HidDevice oNewDevice = (HidDevice)Activator.CreateInstance(oType);
                 oNewDevice.Initialise(strDevicePath);
                 return oNewDevice;
             }
             nIndex++;
         }
     }
     catch(Exception ex)
     {
         throw HidDeviceException.GenerateError(ex.ToString());
     }
     finally
     {
         SetupDiDestroyDeviceInfoList(hInfoSet);
     }
     // No device found.
     return null;
 }
Exemple #14
0
        private String GetDeviceFilename(int vid, int pid)
        {
            string devname  = string.Format("vid_{0:x4}&pid_{1:x4}", vid, pid);
            string filename = null;

            Guid gHid;

            HidD_GetHidGuid(out gHid);

            IntPtr hInfoSet = SetupDiGetClassDevs(ref gHid, null, IntPtr.Zero, DIGCF_DEVICEINTERFACE | DIGCF_PRESENT);

            DeviceInterfaceData oInterface = new DeviceInterfaceData();

            oInterface.Size = Marshal.SizeOf(oInterface);
            int nIndex = 0;

            while (SetupDiEnumDeviceInterfaces(hInfoSet, 0, ref gHid, (uint)nIndex, ref oInterface))
            {
                string strDevicePath = GetDevicePath(hInfoSet, ref oInterface);
                System.Console.WriteLine(strDevicePath);
                if (strDevicePath.IndexOf(devname) >= 0)
                {
                    filename = strDevicePath;
                    break;
                }
                nIndex++;
            }

            SetupDiDestroyDeviceInfoList(hInfoSet);

            return(filename);
        }
Exemple #15
0
        public static String getDevicePath(IntPtr hardwareDeviceInfoPtr, ref DeviceInterfaceData did)
        {
            uint size = 0;

            if (!SetupApi.ClassDev.SetupDiGetDeviceInterfaceDetail(hardwareDeviceInfoPtr, ref did, IntPtr.Zero, 0, ref size, IntPtr.Zero))
            {
                DeviceInterfaceData da = new DeviceInterfaceData();
                da.size = (uint)Marshal.SizeOf(da);

                DeviceInterfaceDetailData detail = new DeviceInterfaceDetailData();
                if (IntPtr.Size == 8)
                {
                    detail.size = 8;
                }
                else
                {
                    detail.size = 4 + (uint)Marshal.SystemDefaultCharSize;
                }

                if (SetupApi.ClassDev.SetupDiGetDeviceInterfaceDetail(hardwareDeviceInfoPtr, ref did, ref detail, size, out size, ref da))
                {
                    return(detail.DevicePath);
                }
                Error.GetLastError();
            }

            return(null);
        }
Exemple #16
0
        /// <summary>
        ///     Helper method to return the device path given a DeviceInterfaceData structure and an InfoSet handle.
        ///     Used in 'FindDevice' so check that method out to see how to get an InfoSet handle and a DeviceInterfaceData.
        /// </summary>
        /// <param name="hInfoSet">Handle to the InfoSet</param>
        /// <param name="oInterface">DeviceInterfaceData structure</param>
        /// <returns>The device path or null if there was some problem</returns>
        private static string GetDevicePath(IntPtr hInfoSet, ref DeviceInterfaceData oInterface)
        {
            uint nRequiredSize = 0;

            // Get the device interface details
            if (
                !SetupDiGetDeviceInterfaceDetail(hInfoSet, ref oInterface, IntPtr.Zero, 0, ref nRequiredSize,
                                                 IntPtr.Zero))
            {
                var detailDataBuffer = Marshal.AllocHGlobal((int)nRequiredSize);
                Marshal.WriteInt32(detailDataBuffer, IntPtr.Size == 4 ? 4 + Marshal.SystemDefaultCharSize : 8);

                try
                {
                    if (SetupDiGetDeviceInterfaceDetail(hInfoSet, ref oInterface, detailDataBuffer, nRequiredSize,
                                                        ref nRequiredSize, IntPtr.Zero))
                    {
                        var pDevicePathName = new IntPtr(detailDataBuffer.ToInt64() + 4);
                        return(Marshal.PtrToStringAnsi(pDevicePathName) ?? string.Empty);
                    }
                }
                finally
                {
                    Marshal.FreeHGlobal(detailDataBuffer);
                }
            }

            return(string.Empty);
        }
Exemple #17
0
 /// <summary>
 /// Initializes a new instance of the <see cref="DeviceEnumerator"/> class.
 /// </summary>
 /// <param name="deviceClass">The identifier of the associated devices.</param>
 /// <param name="flags">The flags used to defined the type of expected devices.</param>
 public DeviceEnumerator(Guid deviceClass, DiGetClassFlags flags)
 {
     this.deviceClass   = deviceClass;
     this.deviceSet     = SetupApiMethods.GetClassDevs(ref deviceClass, null, IntPtr.Zero, flags);
     this.interfaceData = new DeviceInterfaceData();
     this.index         = -1;
 }
Exemple #18
0
        /// <summary>
        /// Helper method to return the device path given a DeviceInterfaceData structure and an InfoSet handle.
        /// Used in 'FindDevice' so check that method out to see how to get an InfoSet handle and a DeviceInterfaceData.
        /// </summary>
        /// <param name="hInfoSet">Handle to the InfoSet</param>
        /// <param name="oInterface">DeviceInterfaceData structure</param>
        /// <returns>The device path or null if there was some problem</returns>
        private static string GetDevicePath(IntPtr hInfoSet, ref DeviceInterfaceData oInterface)
        {
            DeviceInterfaceDetailData oDetail = new DeviceInterfaceDetailData();

            // Size workaround
            if (IntPtr.Size == 8)
            {
                oDetail.Size = 8;
            }
            else
            {
                oDetail.Size = 5;
            }
            Console.WriteLine("Size of struct: {0}", Marshal.SizeOf(oDetail)); // 4 + 256 = 260

            uint nRequiredSize = 0;

            // Error 0
            if (!SetupDiGetDeviceInterfaceDetail(hInfoSet, ref oInterface, IntPtr.Zero, 0, ref nRequiredSize, IntPtr.Zero))
            {
                // Error 122 - ERROR_INSUFFICIENT_BUFFER (not a problem, just used to set nRequiredSize)
                if (SetupDiGetDeviceInterfaceDetail(hInfoSet, ref oInterface, ref oDetail, nRequiredSize, ref nRequiredSize, IntPtr.Zero))
                {
                    return(oDetail.DevicePath);
                }
            }
            // Error 1784 - ERROR_INVALID_USER_BUFFER (unless size=5 on 32bit, size=8 on 64bit)
            return(null);
        }
Exemple #19
0
 public static extern Boolean SetupDiEnumDeviceInterfaces(
     IntPtr hDevInfo,
     IntPtr devInfo,
     ref Guid interfaceClassGuid,
     UInt32 memberIndex,
     ref DeviceInterfaceData deviceInterfaceData
     );
 public static string[] Find(int nVid, int nPid)
 {
     Guid guid;
     List<string> list = new List<string>();
     string str = string.Format("vid_{0:x4}&pid_{1:x4}", nVid, nPid);
     HidD_GetHidGuid(out guid);
     IntPtr lpDeviceInfoSet = SetupDiGetClassDevs(ref guid, null, IntPtr.Zero, 0x12);
     try
     {
         DeviceInterfaceData structure = new DeviceInterfaceData();
         structure.Size = Marshal.SizeOf(structure);
         for (int i = 0; SetupDiEnumDeviceInterfaces(lpDeviceInfoSet, 0, ref guid, (uint)i, ref structure); i++)
         {
             string devicePath = GetDevicePath(lpDeviceInfoSet, ref structure);
             if (devicePath.IndexOf(str) >= 0)
             {
                 list.Add(devicePath);
             }
         }
     }
     finally
     {
         SetupDiDestroyDeviceInfoList(lpDeviceInfoSet);
     }
     return list.ToArray();
 }
Exemple #21
0
        /// <summary>
        /// Helper method to return the device path given a DeviceInterfaceData structure and an InfoSet handle.
        /// Used in 'FindDevice' so check that method out to see how to get an InfoSet handle and a DeviceInterfaceData.
        /// </summary>
        /// <param name="hInfoSet">Handle to the InfoSet</param>
        /// <param name="oInterface">DeviceInterfaceData structure</param>
        /// <returns>The device path or null if there was some problem</returns>
//      private static string GetDevicePath(IntPtr hInfoSet, ref DeviceInterfaceData oInterface)
//      {
//          uint nRequiredSize = 0;
//          // Get the device interface details
//          if (!SetupDiGetDeviceInterfaceDetail(hInfoSet, ref oInterface, IntPtr.Zero, 0, ref nRequiredSize, IntPtr.Zero))
//          {
//              DeviceInterfaceDetailData oDetail = new DeviceInterfaceDetailData();
//              oDetail.Size = 5;	// hardcoded to 5! Sorry, but this works and trying more future proof versions by setting the size to the struct sizeof failed miserably. If you manage to sort it, mail me! Thx
//              if (SetupDiGetDeviceInterfaceDetail(hInfoSet, ref oInterface, ref oDetail, nRequiredSize, ref nRequiredSize, IntPtr.Zero))
//              {
//                  return oDetail.DevicePath;
//              }
//          }
//          return null;
//      }
        #endregion

        #region Public static
        /// <summary>
        /// Finds a device given its PID and VID
        /// </summary>
        /// <param name="nVid">Vendor id for device (VID)</param>
        /// <param name="nPid">Product id for device (PID)</param>
        /// <param name="oType">Type of device class to create</param>
        /// <returns>A new device class of the given type or null</returns>
        public static HIDDevice FindDevice(int nVid, int nPid, Type oType)
        {
            string strPath   = string.Empty;
            string strSearch = string.Format("vid_{0:x4}&pid_{1:x4}", nVid, nPid);             // first, build the path search string
            Guid   gHid;

            HidD_GetHidGuid(out gHid);                                                                                 // next, get the GUID from Windows that it uses to represent the HID USB interface
            IntPtr hInfoSet = SetupDiGetClassDevs(ref gHid, null, IntPtr.Zero, DIGCF_DEVICEINTERFACE | DIGCF_PRESENT); // this gets a list of all HID devices currently connected to the computer (InfoSet)

            try
            {
                DeviceInterfaceData oInterface = new DeviceInterfaceData();     // build up a device interface data block
                oInterface.Size = Marshal.SizeOf(oInterface);
                // Now iterate through the InfoSet memory block assigned within Windows in the call to SetupDiGetClassDevs
                // to get device details for each device connected
                int nIndex = 0;
                while (SetupDiEnumDeviceInterfaces(hInfoSet, 0, ref gHid, (uint)nIndex, ref oInterface)) // this gets the device interface information for a device at index 'nIndex' in the memory block
                {
                    string strDevicePath = GetDevicePath(hInfoSet, ref oInterface);                      // get the device path (see helper method 'GetDevicePath')
                    //if (strDevicePath.IndexOf(strSearch) >= 0)	// do a string search, if we find the VID/PID string then we found our device!
                    {
                        HIDDevice oNewDevice = (HIDDevice)Activator.CreateInstance(oType); // create an instance of the class for this device
                        oNewDevice.Initialise(strDevicePath);                              // initialise it with the device path
                        return(oNewDevice);                                                // and return it
                    }
                    nIndex++;                                                              // if we get here, we didn't find our device. So move on to the next one.
                }
            }
            finally
            {
                // Before we go, we have to free up the InfoSet memory reserved by SetupDiGetClassDevs
                SetupDiDestroyDeviceInfoList(hInfoSet);
            }
            return(null);        // oops, didn't find our device
        }
Exemple #22
0
 public static extern Boolean SetupDiGetDeviceInterfaceDetail(
     IntPtr hDevInfo,
     ref DeviceInterfaceData deviceInterfaceData,
     ref DeviceInterfaceDetailData deviceInterfaceDetailData,
     uint deviceInterfaceDetailDataSize,
     out uint requiredSize,
     IntPtr deviceInfoData
     );
Exemple #23
0
 public static extern Boolean SetupDiGetDeviceInterfaceDetail(
     IntPtr hDevInfo,
     ref DeviceInterfaceData deviceInterfaceData,
     IntPtr deviceInterfaceDetailData,
     UInt32 deviceInterfaceDetailDataSize,
     ref UInt32 requiredSize,
     IntPtr deviceInfoData
     );
Exemple #24
0
 protected static extern bool SetupDiGetDeviceRegistryProperty(
     IntPtr DeviceInfoSet,
     ref DeviceInterfaceData DeviceInfoData,
     uint Property,
     out UInt32 PropertyRegDataType,
     byte[] PropertyBuffer, // the difference between this signature and the one above.
     uint PropertyBufferSize,
     out UInt32 RequiredSize
     );
Exemple #25
0
        public static string SetupDiGetDeviceInterfaceDetail(
            SafeDeviceInfoSetHandle lpDeviceInfoSet,
            DeviceInterfaceData oInterfaceData,
            IntPtr lpDeviceInfoData)
        {
            var requiredSize = new NullableUInt32();

            // First call to get the size to allocate
            SetupDiGetDeviceInterfaceDetail(
                lpDeviceInfoSet,
                ref oInterfaceData,
                IntPtr.Zero,
                0,
                requiredSize,
                null);

            // As we passed an empty buffer we know that the function will fail, not need to check the result.
            var lastError = GetLastError();
            if (lastError != Win32ErrorCode.ERROR_INSUFFICIENT_BUFFER)
            {
                throw new Win32Exception(lastError);
            }

            var buffer = Marshal.AllocHGlobal((int)requiredSize.Value);

            try
            {
                Marshal.WriteInt32(buffer, DeviceInterfaceDetailDataSize.Value);

                // Second call to get the value
                var success = SetupDiGetDeviceInterfaceDetail(
                    lpDeviceInfoSet,
                    ref oInterfaceData,
                    buffer,
                    (uint)requiredSize,
                    null,
                    null);

                if (!success)
                {
                    Marshal.ThrowExceptionForHR(Marshal.GetHRForLastWin32Error());
                    return null;
                }

                var strPtr = new IntPtr(buffer.ToInt64() + 4);
                return Marshal.PtrToStringAuto(strPtr);
            }
            finally
            {
                Marshal.FreeHGlobal(buffer);
            }
        }
        public static List <HIDDeviceAvalible> GetDevicesListByVID(int nVid)
        {
            List <HIDDeviceAvalible> devices = new List <HIDDeviceAvalible>();
            string strSearch = string.Format("vid_{0:x4}&pid_", nVid);
            Guid   gHid;

            HidD_GetHidGuid(out gHid);

            IntPtr hInfoSet = SetupDiGetClassDevs(ref gHid, null, IntPtr.Zero, DIGCF_DEVICEINTERFACE | DIGCF_PRESENT);

            try
            {
                uint nIndex = 0;
                DeviceInterfaceData oInterface = new DeviceInterfaceData();
                oInterface.Size = Marshal.SizeOf(oInterface);

                while (SetupDiEnumDeviceInterfaces(hInfoSet, 0, ref gHid, nIndex, ref oInterface))
                {
                    string strDevicePath = GetDevicePath(hInfoSet, ref oInterface);
                    if (strDevicePath.IndexOf(strSearch) >= 0)
                    {
                        HIDDeviceAvalible device = new HIDDeviceAvalible();
                        device.Path        = strDevicePath;
                        device.Description = HIDDevice.GetProductString(device.Path);

                        int    cut       = device.Path.IndexOf("vid_");
                        string xid_start = device.Path.Substring(cut + 4);
                        device.VendorId = Convert.ToUInt16(xid_start.Substring(0, 4), 16);

                        cut              = device.Path.IndexOf("pid_");
                        xid_start        = device.Path.Substring(cut + 4);
                        device.ProductId = Convert.ToUInt16(xid_start.Substring(0, 4), 16);

                        if (!String.IsNullOrEmpty(device.Description))
                        {
                            devices.Add(device);
                        }
                    }
                    nIndex++;
                }
            }
            catch (Exception ex)
            {
                throw HIDDeviceException.GenerateError(ex.ToString());
            }
            finally
            {
                SetupDiDestroyDeviceInfoList(hInfoSet);
            }

            return(devices);
        }
 private static string GetDevicePath(IntPtr hInfoSet, ref DeviceInterfaceData oInterface)
 {
     uint nRequiredSize = 0;
     if (!SetupDiGetDeviceInterfaceDetail(hInfoSet, ref oInterface, IntPtr.Zero, 0, ref nRequiredSize, IntPtr.Zero))
     {
         DeviceInterfaceDetailData oDetailData = new DeviceInterfaceDetailData();
         oDetailData.Size = 5;
         if (SetupDiGetDeviceInterfaceDetail(hInfoSet, ref oInterface, ref oDetailData, nRequiredSize, ref nRequiredSize, IntPtr.Zero))
         {
             return oDetailData.DevicePath;
         }
     }
     return null;
 }
Exemple #28
0
        private static string GetDevicePath(IntPtr hInfoSet, ref DeviceInterfaceData oInterface)
        {
            uint nRequiredSize = 0;

            if (!SetupDiGetDeviceInterfaceDetail(hInfoSet, ref oInterface, IntPtr.Zero, 0, ref nRequiredSize, IntPtr.Zero))
            {
                DeviceInterfaceDetailData oDetail = new DeviceInterfaceDetailData();
                oDetail.Size = (IntPtr.Size == 8) ? 8 : 5;
                if (SetupDiGetDeviceInterfaceDetail(hInfoSet, ref oInterface, ref oDetail, nRequiredSize, ref nRequiredSize, IntPtr.Zero))
                {
                    return(oDetail.DevicePath);
                }
            }
            return(null);
        }
Exemple #29
0
        /// <summary>
        /// 连接USB设备的函数
        /// </summary>
        /// <returns>成功连接则返回OK,否则返回连接失败原因</returns>
        public static COMMUNICATERESULT connect()
        {
            COMMUNICATERESULT ret;
            string            strPath   = string.Empty;
            string            strSearch = string.Format("vid_{0:x4}&pid_{1:x4}", nVid, nPid);                          // first, build the path search string
            Guid   gHid     = HIDGuid;
            IntPtr hInfoSet = SetupDiGetClassDevs(ref gHid, null, IntPtr.Zero, DIGCF_DEVICEINTERFACE | DIGCF_PRESENT); // this gets a list of all HID devices currently connected to the computer (InfoSet)

            try
            {
                DeviceInterfaceData oInterface = new DeviceInterfaceData();     // build up a device interface data block
                oInterface.Size = Marshal.SizeOf(oInterface);
                // Now iterate through the InfoSet memory block assigned within Windows in the call to SetupDiGetClassDevs
                // to get device details for each device connected
                int nIndex = 0;
                while (SetupDiEnumDeviceInterfaces(hInfoSet, 0, ref gHid, (uint)nIndex, ref oInterface)) // this gets the device interface information for a device at index 'nIndex' in the memory block
                {
                    string strDevicePath = GetDevicePath(hInfoSet, ref oInterface);                      // get the device path (see helper method 'GetDevicePath')

                    if (strDevicePath.IndexOf(strSearch) >= 0)                                           // do a string search, if we find the VID/PID string then we found our device!
                    {
                        ret = InitialiseFile(strDevicePath);
                        if (ret == COMMUNICATERESULT.OK)
                        {
                            HidExist = true;
                        }
                        else
                        {
                            HidExist = false;
                        }
                        return(ret);
                    }
                    nIndex++;   // if we get here, we didn't find our device. So move on to the next one.
                }
            }
            catch (Exception)
            {
                HidExist = false;
                return(COMMUNICATERESULT.USB_Exception);
            }
            finally
            {
                // Before we go, we have to free up the InfoSet memory reserved by SetupDiGetClassDevs
                SetupDiDestroyDeviceInfoList(hInfoSet);
            }
            HidExist = false;
            return(COMMUNICATERESULT.USB_NeverFoundDevice);
        }
Exemple #30
0
        /// <summary>
        /// Helper method to return the device path given a DeviceInterfaceData structure and an InfoSet handle.
        /// Used in 'FindDevice' so check that method out to see how to get an InfoSet handle and a DeviceInterfaceData.
        /// </summary>
        /// <param name="hInfoSet">Handle to the InfoSet</param>
        /// <param name="oInterface">DeviceInterfaceData structure</param>
        /// <returns>The device path or null if there was some problem</returns>
        private static string GetDevicePath(IntPtr hInfoSet, ref DeviceInterfaceData oInterface)
        {
            uint nRequiredSize = 0;

            // Get the device interface details
            if (!SetupDiGetDeviceInterfaceDetail(hInfoSet, ref oInterface, IntPtr.Zero, 0, ref nRequiredSize, IntPtr.Zero))
            {
                DeviceInterfaceDetailData oDetail = new DeviceInterfaceDetailData();
                oDetail.Size = 5;       // hardcoded to 5! Sorry, but this works and trying more future proof versions by setting the size to the struct sizeof failed miserably. If you manage to sort it, mail me! Thx
                if (SetupDiGetDeviceInterfaceDetail(hInfoSet, ref oInterface, ref oDetail, nRequiredSize, ref nRequiredSize, IntPtr.Zero))
                {
                    return(oDetail.DevicePath);
                }
            }
            return(null);
        }
Exemple #31
0
        /// <summary>
        /// Finds a device given its PID and VID
        /// </summary>
        /// <param name="nVid">Vendor id for device (VID)</param>
        /// <param name="nPid">Product id for device (PID)</param>
        /// <param name="oType">Type of device class to create</param>
        /// <returns>A new device class of the given type or null</returns>
        public static HIDDevice FindDevice(int nVid, int nPid, Type oType)
        {
            string strPath   = string.Empty;
            string strSearch = string.Format("vid_{0:x4}&pid_{1:x4}", nVid, nPid); // first, build the path search string
            Guid   gHid      = HIDGuid;
            //HidD_GetHidGuid(out gHid);	// next, get the GUID from Windows that it uses to represent the HID USB interface
            IntPtr hInfoSet = SetupDiGetClassDevs(ref gHid, null, IntPtr.Zero, DIGCF_DEVICEINTERFACE | DIGCF_PRESENT);  // this gets a list of all HID devices currently connected to the computer (InfoSet)


            try
            {
                DeviceInterfaceData oInterface = new DeviceInterfaceData();     // build up a device interface data block
                oInterface.Size = Marshal.SizeOf(oInterface);
                // Now iterate through the InfoSet memory block assigned within Windows in the call to SetupDiGetClassDevs
                // to get device details for each device connected
                int nIndex = 0;
                while (SetupDiEnumDeviceInterfaces(hInfoSet, 0, ref gHid, (uint)nIndex, ref oInterface)) // this gets the device interface information for a device at index 'nIndex' in the memory block
                {
                    string strDevicePath = GetDevicePath(hInfoSet, ref oInterface);                      // get the device path (see helper method 'GetDevicePath')
                    if (strDevicePath.IndexOf(strSearch) >= 0)                                           // do a string search, if we find the VID/PID string then we found our device!
                    {
                        HIDDevice oNewDevice = (HIDDevice)Activator.CreateInstance(oType);               // create an instance of the class for this device
                        oNewDevice.Initialise(strDevicePath);                                            // initialise it with the device path
                        return(oNewDevice);                                                              // and return it
                    }
                    nIndex++;                                                                            // if we get here, we didn't find our device. So move on to the next one.
                }

                //   MessageBox.Show("请检查是否插入设备!");
            }
            catch (Exception ex)
            {
                throw HIDDeviceException.GenerateError(ex.ToString());
                //Console.WriteLine(ex.ToString());
            }
            finally
            {
                // Before we go, we have to free up the InfoSet memory reserved by SetupDiGetClassDevs
                SetupDiDestroyDeviceInfoList(hInfoSet);
            }
            //string a = @"\\?\hid#vid_0483&pid_5750#7&2e4989f7&0&0000#{4d1e55b2-f16f-11cf-88cb-001111000030}";
            //HIDDevice oNewDevice1 = (HIDDevice)Activator.CreateInstance(oType);
            //oNewDevice1.Initialise(a);	// initialise it with the device path
            //return oNewDevice1;
            return(null);        // oops, didn't find our device
        }
Exemple #32
0
        /// <summary>
        /// Get USB HID device path
        /// </summary>
        private static string GetDevicePath(IntPtr hInfoSet, ref DeviceInterfaceData oInterface)
        {
            uint nRequiredSize = 0;

            if (SetupDiGetDeviceInterfaceDetail(hInfoSet, ref oInterface, IntPtr.Zero, 0, ref nRequiredSize, IntPtr.Zero) == false)
            {
                // TODO: Find a solution
                // Tip: http://stackoverflow.com/questions/1054748/setupdigetdeviceinterfacedetail-unexplainable-error
                //throw new HIDDeviceException();
            }
            var oDetail = new DeviceInterfaceDetailData();

            oDetail.Size = Marshal.SizeOf(typeof(IntPtr)) == 8 ? 8 : 5;             // x86/x64 magic...
            if (SetupDiGetDeviceInterfaceDetail(hInfoSet, ref oInterface, ref oDetail, nRequiredSize, ref nRequiredSize, IntPtr.Zero) == false)
            {
                throw new Win32Exception();
            }
            return(oDetail.DevicePath);
        }
Exemple #33
0
        /// <summary>
        /// Finds devices of type.
        /// </summary>
        /// <typeparam name="TDevice">Type of device to look for.</typeparam>
        /// <returns>Enumeration of devices.</returns>
        public static IEnumerable <DeviceDescription <TDevice> > FindDevices <TDevice>() where  TDevice : HIDDevice
        {
            var devices = new List <DeviceDescription <TDevice> >();
            //Creating instance to get Vendor and product id's.

            var instance = (TDevice)Activator.CreateInstance(typeof(TDevice), new[] { "" });

            var strSearch = string.Format("vid_{0:x4}&pid_{1:x4}", instance.VendorId, instance.ProductId); // first, build the path search string
            var gHid      = HIDGuid;
            //HidD_GetHidGuid(out gHid);	// next, get the GUID from Windows that it uses to represent the HID USB interface
            var hInfoSet = SetupDiGetClassDevs(ref gHid, null, IntPtr.Zero, DIGCF_DEVICEINTERFACE | DIGCF_PRESENT);     // this gets a list of all HID devices currently connected to the computer (InfoSet)

            try
            {
                var oInterface = new DeviceInterfaceData();     // build up a device interface data block
                oInterface.Size = Marshal.SizeOf(oInterface);
                // Now iterate through the InfoSet memory block assigned within Windows in the call to SetupDiGetClassDevs
                // to get device details for each device connected
                var nIndex = 0;
                while (SetupDiEnumDeviceInterfaces(hInfoSet, 0, ref gHid, (uint)nIndex, ref oInterface)) // this gets the device interface information for a device at index 'nIndex' in the memory block
                {
                    string strDevicePath = GetDevicePath(hInfoSet, ref oInterface);                      // get the device path (see helper method 'GetDevicePath')
                    if (strDevicePath.IndexOf(strSearch) >= 0)                                           // do a string search, if we find the VID/PID string then we found our device!
                    {
                        // Creating instance and adding device path as constructor parameter.
                        var oNewDevice = (DeviceDescription <TDevice>)Activator.CreateInstance(typeof(DeviceDescription <TDevice>), new[] { strDevicePath });
                        devices.Add(oNewDevice);
                    }
                    nIndex++;   // if we get here, we didn't find our device. So move on to the next one.
                }
            }
            catch (Exception ex)
            {
                throw HIDDeviceException.GenerateError(ex.ToString());
            }
            finally
            {
                // Before we go, we have to free up the InfoSet memory reserved by SetupDiGetClassDevs
                SetupDiDestroyDeviceInfoList(hInfoSet);
            }
            return(devices);
        }
Exemple #34
0
        static bool GetDeviceInfoByIndex(IntPtr infoSetPtr, ref Guid hidGuid, uint deviceIndex, out DeviceInformation deviceInfo)
        {
            var interfaceData = new DeviceInterfaceData();

            interfaceData.Size = Marshal.SizeOf(interfaceData); // 28 in 32bit or 32 in 64bit mode

            if (SetupDiEnumDeviceInterfaces(infoSetPtr, IntPtr.Zero, ref hidGuid, deviceIndex, ref interfaceData))
            {
                var deviceInfoData = new DeviceInfoData();
                deviceInfoData.Size = (uint)Marshal.SizeOf(deviceInfoData);

                if (SetupDiEnumDeviceInfo(infoSetPtr, deviceIndex, ref deviceInfoData))
                {
                    deviceInfo = new DeviceInformation
                                 (
                        path: GetDevicePath(infoSetPtr, ref interfaceData),
                        description: ReadPropertyString(infoSetPtr, ref deviceInfoData, RegistryProperty.DeviceDescription)
                                 );
                    return(true);
                }
            }

            if (ERROR_NO_MORE_ITEMS == Marshal.GetLastWin32Error())
            {
                deviceInfo = new DeviceInformation();
                return(false); // Do nothing, this just means the device wasn't found
            }

            // Load system error message
            var exception = new Win32Exception(Marshal.GetLastWin32Error())
            {
                Source = "WinUSB.SetupDiEnumDeviceInterfaces"
            };

            if (ERROR_INVALID_USER_BUFFER == Marshal.GetLastWin32Error())
            {
                // Property infoSetPtr.Size was not set correctly (must be 5 for 32bit or 8 for 64bit)
                throw new Exception(Errors.Invalid_InfoSet_Size, exception);
            }

            throw exception;
        }
Exemple #35
0
        static string GetDevicePath(IntPtr infoSetPtr, ref DeviceInterfaceData interfaceData)
        {
            var interfaceDetailData = new DeviceInterfaceDetailData
            {
                Size = Environment.Is64BitProcess ? 8 : 5
            };

            // Query needed structure size
            uint requiredSize = 0;

            if (SetupDiGetDeviceInterfaceDetail(infoSetPtr, ref interfaceData, IntPtr.Zero, 0, ref requiredSize, IntPtr.Zero))
            {
                return(string.Empty); // Device has no path (because request was successful without memory for the path).
                                      // Just skip it. Theoretically, there should be not such devices.
            }

            // Check we have enough space in details structure
            if (requiredSize > Marshal.SizeOf(interfaceDetailData))
            {
                var errorMessage =
                    string.Format(Errors.Insufficient_Path_Buffer_0,
                                  requiredSize - Marshal.SizeOf(interfaceDetailData.Size));

                throw new InsufficientMemoryException(errorMessage)
                      {
                          Source = "WinUSB.SetupDiGetDeviceInterfaceDetail"
                      };
            }

            // Request device path
            if (SetupDiGetDeviceInterfaceDetail(infoSetPtr, ref interfaceData, ref interfaceDetailData,
                                                requiredSize, ref requiredSize, IntPtr.Zero))
            {
                return(interfaceDetailData.DevicePath);
            }

            throw new Win32Exception(Marshal.GetLastWin32Error())
                  {
                      Source = "WinUSB.SetupDiGetDeviceInterfaceDetail"
                  };
        }
Exemple #36
0
        /// <summary>
        /// Finds a device given its PID and VID
        /// </summary>
        /// <param name="nVid">Vendor id for device (VID)</param>
        /// <param name="nPid">Product id for device (PID)</param>
        /// <param name="oType">Type of device class to create</param>
        /// <returns>A new device class of the given type or null</returns>
        public static USBDevice FindDevice(int nVid, int nPid, Type oType)
        {
            string strPath = string.Empty;
            string strSearch = string.Format("vid_{0:x4}&pid_{1:x4}", nVid, nPid); // first, build the path search string
            Guid gHid = new Guid("{0x28d78fad,0x5a12,0x11D1,{0xae,0x5b,0x00,0x00,0xf8,0x03,0xa8,0xc2}}");

            //HidD_GetHidGuid(out gHid);	// next, get the GUID from Windows that it uses to represent the HID USB interface
            IntPtr hInfoSet = SetupDiGetClassDevs(ref gHid, null, IntPtr.Zero, DIGCF_DEVICEINTERFACE | DIGCF_PRESENT);// this gets a list of all HID devices currently connected to the computer (InfoSet)
            try
            {
                DeviceInterfaceData oInterface = new DeviceInterfaceData();	// build up a device interface data block
                oInterface.Size = Marshal.SizeOf(oInterface);
                // Now iterate through the InfoSet memory block assigned within Windows in the call to SetupDiGetClassDevs
                // to get device details for each device connected
                int nIndex = 0;
                System.Console.WriteLine(gHid.ToString());
                System.Console.WriteLine(hInfoSet.ToString());
                Boolean Result = SetupDiEnumDeviceInterfaces(hInfoSet, 0, ref gHid, (uint)nIndex, ref oInterface);
                System.Console.WriteLine(Result.ToString());
                while (SetupDiEnumDeviceInterfaces(hInfoSet, 0, ref gHid, (uint)nIndex, ref oInterface))	// this gets the device interface information for a device at index 'nIndex' in the memory block
                    {
                        string strDevicePath = GetDevicePath(hInfoSet, ref oInterface);	// get the device path (see helper method 'GetDevicePath')
                        if (strDevicePath.IndexOf(strSearch) >= 0)	// do a string search, if we find the VID/PID string then we found our device!
                        {
                            USBDevice oNewDevice = (USBDevice)Activator.CreateInstance(oType);	// create an instance of the class for this device
                            //USBPRINT\VID_088c&PID_2030
                            oNewDevice.Initialise(strDevicePath);	// strDevicePath initialise it with the device path
                            return oNewDevice;	// and return it
                        }
                        nIndex++;	// if we get here, we didn't find our device. So move on to the next one.
                    }
                    System.Console.WriteLine(Marshal.GetLastWin32Error().ToString());
            }
            finally
            {
                // Before we go, we have to free up the InfoSet memory reserved by SetupDiGetClassDevs
                SetupDiDestroyDeviceInfoList(hInfoSet);
            }
            return null;	// oops, didn't find our device
        }
Exemple #37
0
        /// <summary>
        ///     Finds a device given its PID and VID
        /// </summary>
        private bool FindDevice(int nVid, int nPid)
        {
            var strSearch = string.Format("vid_{0:x4}&pid_{1:x4}", nVid, nPid); // first, build the path search string
            var gHid      = ClassGuid;                                          // next, get the GUID from Windows that it uses to represent the HID USB interface
            var hInfoSet  = SetupDiGetClassDevs(ref gHid, null, IntPtr.Zero, DIGCF_DEVICEINTERFACE | DIGCF_PRESENT);

            // this gets a list of all HID devices currently connected to the computer (InfoSet)

            try
            {
                var oInterface = new DeviceInterfaceData(); // build up a device interface data block
                oInterface.Size = Marshal.SizeOf(oInterface);
                // Now iterate through the InfoSet memory block assigned within Windows in the call to SetupDiGetClassDevs
                // to get device details for each device connected
                var nIndex = 0;
                while (SetupDiEnumDeviceInterfaces(hInfoSet, 0, ref gHid, (uint)nIndex, ref oInterface))
                // this gets the device interface information for a device at index 'nIndex' in the memory block
                {
                    var strDevicePath = GetDevicePath(hInfoSet, ref oInterface);
                    // get the device path (see helper method 'GetDevicePath')
                    if (strDevicePath.IndexOf(strSearch, StringComparison.Ordinal) >= 0)
                    // do a string search, if we find the VID/PID string then we found our device!
                    {
                        return(true);
                    }
                    nIndex++; // if we get here, we didn't find our device. So move on to the next one.
                }
            }
            catch (Exception)
            {
                return(false);
            }
            finally
            {
                // Before we go, we have to free up the InfoSet memory reserved by SetupDiGetClassDevs
                SetupDiDestroyDeviceInfoList(hInfoSet);
            }
            return(false); // oops, didn't find our device
        }
Exemple #38
0
 public static extern bool SetupDiGetDeviceInterfaceDetail(
   IntPtr handle,
   ref DeviceInterfaceData deviceInterfaceData,
   ref DeviceInterfaceDetailData deviceInterfaceDetailData,
   uint detailSize,
   IntPtr unused1,
   IntPtr unused2);
Exemple #39
0
 public static extern bool SetupDiGetDeviceInterfaceDetail(
   IntPtr handle,
   ref DeviceInterfaceData deviceInterfaceData,
   IntPtr unused1,
   int unused2,
   ref uint requiredSize,
   IntPtr unused3);
 protected static extern bool SetupDiEnumDeviceInterfaces(IntPtr lpDeviceInfoSet, uint nDeviceInfoData, ref Guid gClass, uint nIndex, ref DeviceInterfaceData oInterfaceData);
Exemple #41
0
		/// <summary>
		/// Gets the DeviceInterfaceData for a device from an InfoSet.
		/// </summary>
		/// <param name="lpDeviceInfoSet">InfoSet to access</param>
		/// <param name="nDeviceInfoData">Not used</param>
		/// <param name="gClass">Device class guid</param>
		/// <param name="nIndex">Index into InfoSet for device</param>
		/// <param name="oInterfaceData">DeviceInterfaceData to fill with data</param>
		/// <returns>True if successful, false if not (e.g. when index is passed end of InfoSet)</returns>
        [DllImport("setupapi.dll", SetLastError = true)] internal static extern bool SetupDiEnumDeviceInterfaces(IntPtr lpDeviceInfoSet, IntPtr nDeviceInfoData, ref Guid gClass, Int32 nIndex, ref DeviceInterfaceData oInterfaceData);
Exemple #42
0
		public bool SetupDiGetDeviceInterfaceDetail(
            SafeDeviceInfoSetHandle deviceInfoSet,
            ref DeviceInterfaceData deviceInterfaceData,
            IntPtr deviceInterfaceDetailData,
            uint deviceInterfaceDetailDataSize,
            NullableUInt32 requiredSize,
            DeviceInfoData deviceInfoData)
			=> SetupDiGetDeviceInterfaceDetail(deviceInfoSet, ref deviceInterfaceData, deviceInterfaceDetailData, deviceInterfaceDetailDataSize, requiredSize, deviceInfoData);
Exemple #43
0
		/// <summary>
		/// Gets the DeviceInterfaceData for a device from an InfoSet.
		/// </summary>
		/// <param name="lpDeviceInfoSet">InfoSet to access</param>
		/// <param name="nDeviceInfoData">Not used</param>
		/// <param name="gClass">Device class guid</param>
		/// <param name="nIndex">Index into InfoSet for device</param>
		/// <param name="oInterfaceData">DeviceInterfaceData to fill with data</param>
		/// <returns>True if successful, false if not (e.g. when index is passed end of InfoSet)</returns>
        [DllImport("setupapi.dll", SetLastError = true)] protected static extern bool SetupDiEnumDeviceInterfaces(IntPtr lpDeviceInfoSet, uint nDeviceInfoData, ref Guid gClass, uint nIndex, ref DeviceInterfaceData oInterfaceData);
Exemple #44
0
		/// <summary>
		/// Finds a device given its PID and VID
		/// </summary>
		/// <param name="nVid">Vendor id for device (VID)</param>
		/// <param name="nPid">Product id for device (PID)</param>
		/// <param name="oType">Type of device class to create</param>
		/// <returns>A new device class of the given type or null</returns>
		public static HIDDevice FindDevice(int nVid, int nPid, Type oType)
        {
            string strPath = string.Empty;
            string strSearch = @"#vid_" + nVid.ToString("x4") + "&pid_" + nPid.ToString("x4") + "#";
            //string strSearch = string.Format("VID_{0:X4}&PID_{1:X4}", nVid, nPid); // first, build the path search string
            Guid gHid = HIDGuid;
            HidD_GetHidGuid(ref gHid);	// next, get the GUID from Windows that it uses to represent the HID USB interface
            IntPtr hInfoSet = SetupDiGetClassDevs(ref gHid, IntPtr.Zero, IntPtr.Zero, DIGCF_DEVICEINTERFACE | DIGCF_PRESENT);   // this gets a list of all HID devices currently connected to the computer (InfoSet)
            try
            {
                var oInterface = new DeviceInterfaceData();	// build up a device interface data block
                oInterface.Size = Marshal.SizeOf(oInterface);
                //oInterface.Size = (IntPtr.Size == 4) ? (4 + Marshal.SystemDefaultCharSize) : 8;
                // Now iterate through the InfoSet memory block assigned within Windows in the call to SetupDiGetClassDevs
                // to get device details for each device connected
                int nIndex = 0;
                while (SetupDiEnumDeviceInterfaces(hInfoSet, IntPtr.Zero, ref gHid, nIndex, ref oInterface))	// this gets the device interface information for a device at index 'nIndex' in the memory block
                {
                    string strDevicePath = GetDevicePath(hInfoSet, ref oInterface);	// get the device path (see helper method 'GetDevicePath')
                    if (strDevicePath.IndexOf(strSearch) >= 0)	// do a string search, if we find the VID/PID string then we found our device!
                    {
                        HIDDevice oNewDevice = (HIDDevice)Activator.CreateInstance(oType);	// create an instance of the class for this device
                        oNewDevice.Initialise(strDevicePath);	// initialise it with the device path
                        return oNewDevice;	// and return it
                    }
                    nIndex++;	// if we get here, we didn't find our device. So move on to the next one.
                }
            }
            catch(Exception ex)
            {
                throw HIDDeviceException.GenerateError(ex.ToString());
                //Console.WriteLine(ex.ToString());
            }
            finally
            {
				// Before we go, we have to free up the InfoSet memory reserved by SetupDiGetClassDevs
                SetupDiDestroyDeviceInfoList(hInfoSet);
            }
            return null;	// oops, didn't find our device
        }
    /// <summary>
    /// Find the device path for the supplied Device Class Guid.
    /// </summary>
    /// <param name="classGuid">GUID to locate device with.</param>
    /// <returns>Device path.</returns>
    public static string Find(Guid classGuid)
    {
      IntPtr handle = SetupDiGetClassDevs(ref classGuid, null, IntPtr.Zero, Digcfs.DeviceInterface | Digcfs.Present);

      if (handle.ToInt32() == -1)
        return null;

      for (int deviceIndex = 0;; deviceIndex++)
      {
        DeviceInfoData deviceInfoData = new DeviceInfoData();
        deviceInfoData.Size = Marshal.SizeOf(deviceInfoData);

        if (!SetupDiEnumDeviceInfo(handle, deviceIndex, ref deviceInfoData))
        {
          int lastError = Marshal.GetLastWin32Error();

          // out of devices or do we have an error?
          if (lastError != ErrorNoMoreItems && lastError != ErrorModNotFound)
          {
            SetupDiDestroyDeviceInfoList(handle);
            throw new Win32Exception(lastError);
          }

          SetupDiDestroyDeviceInfoList(handle);
          break;
        }

        DeviceInterfaceData deviceInterfaceData = new DeviceInterfaceData();
        deviceInterfaceData.Size = Marshal.SizeOf(deviceInterfaceData);

        if (!SetupDiEnumDeviceInterfaces(handle, ref deviceInfoData, ref classGuid, 0, ref deviceInterfaceData))
        {
          SetupDiDestroyDeviceInfoList(handle);
          throw new Win32Exception(Marshal.GetLastWin32Error());
        }

        uint cbData = 0;

        if (
          !SetupDiGetDeviceInterfaceDetail(handle, ref deviceInterfaceData, IntPtr.Zero, 0, ref cbData, IntPtr.Zero) &&
          cbData == 0)
        {
          SetupDiDestroyDeviceInfoList(handle);
          throw new Win32Exception(Marshal.GetLastWin32Error());
        }

        DeviceInterfaceDetailData deviceInterfaceDetailData = new DeviceInterfaceDetailData();
        if (IntPtr.Size == 8)
          deviceInterfaceDetailData.Size = 8;
        else
          deviceInterfaceDetailData.Size = 5;


        if (
          !SetupDiGetDeviceInterfaceDetail(handle, ref deviceInterfaceData, ref deviceInterfaceDetailData, cbData,
                                           IntPtr.Zero, IntPtr.Zero))
        {
          SetupDiDestroyDeviceInfoList(handle);
          throw new Win32Exception(Marshal.GetLastWin32Error());
        }

        if (!String.IsNullOrEmpty(deviceInterfaceDetailData.DevicePath))
        {
          SetupDiDestroyDeviceInfoList(handle);
          return deviceInterfaceDetailData.DevicePath;
        }
      }

      return null;
    }
        /// <summary>
        /// Helper method to return the device path given a DeviceInterfaceData structure and an InfoSet handle.
        /// Used in 'FindDevice' so check that method out to see how to get an InfoSet handle and a DeviceInterfaceData.
        /// </summary>
        /// <param name="hInfoSet">Handle to the InfoSet</param>
        /// <param name="oInterface">DeviceInterfaceData structure</param>
        /// <returns>The device path or null if there was some problem</returns>
        private static string GetDevicePath(IntPtr hInfoSet, ref DeviceInterfaceData oInterface)
        {
            uint nRequiredSize = 0;
            // Get the device interface details
            if (!SetupDiGetDeviceInterfaceDetail(hInfoSet, ref oInterface, IntPtr.Zero, 0, ref nRequiredSize, IntPtr.Zero))
            {
                DeviceInterfaceDetailData oDetail = new DeviceInterfaceDetailData();
                bool is64BitProcess;
                IsWow64Process(Process.GetCurrentProcess().Handle, out is64BitProcess);

                oDetail.Size = (IntPtr.Size == 8 || (IntPtr.Size == 4 && is64BitProcess)) ? 8 : 5;
                if (SetupDiGetDeviceInterfaceDetail(hInfoSet, ref oInterface, ref oDetail, nRequiredSize, ref nRequiredSize, IntPtr.Zero))
                {
                    return oDetail.DevicePath;
                }
            }
            return null;
        }
Exemple #47
0
        /// <summary>
        /// Helper method to return the device path given a DeviceInterfaceData structure and an InfoSet handle.
        /// Used in 'FindDevice' so check that method out to see how to get an InfoSet handle and a DeviceInterfaceData.
        /// </summary>
        /// <param name="hInfoSet">Handle to the InfoSet</param>
        /// <param name="oInterface">DeviceInterfaceData structure</param>
        /// <returns>The device path or null if there was some problem</returns>
        private static string GetDevicePath(IntPtr hInfoSet, ref DeviceInterfaceData oInterface)
        {
            DeviceInterfaceDetailData oDetail = new DeviceInterfaceDetailData();
            // Size workaround
            if (IntPtr.Size == 8)
                oDetail.Size = 8;
            else
                oDetail.Size = 5;
            Console.WriteLine("Size of struct: {0}", Marshal.SizeOf(oDetail)); // 4 + 256 = 260

            uint nRequiredSize = 0;

            // Error 0
            if (!SetupDiGetDeviceInterfaceDetail(hInfoSet, ref oInterface, IntPtr.Zero, 0, ref nRequiredSize, IntPtr.Zero))
                // Error 122 - ERROR_INSUFFICIENT_BUFFER (not a problem, just used to set nRequiredSize)
                if (SetupDiGetDeviceInterfaceDetail(hInfoSet, ref oInterface, ref oDetail, nRequiredSize, ref nRequiredSize, IntPtr.Zero))
                    return oDetail.DevicePath;
            // Error 1784 - ERROR_INVALID_USER_BUFFER (unless size=5 on 32bit, size=8 on 64bit)
            return null;
        }
 internal static extern bool SetupDiGetDeviceInterfaceDetail(IntPtr deviceInfoSet, ref DeviceInterfaceData deviceInterfaceData, ref DeviceInterfaceDetailData deviceInterfaceDetailData, int deviceInterfaceDetailDataSize, ref int requiredSize, IntPtr deviceInfoData);
 internal static extern bool SetupDiEnumDeviceInterfaces(IntPtr deviceInfoSet, ref DeviceInfoData deviceInfoData, ref Guid interfaceClassGuid, int memberIndex, ref DeviceInterfaceData deviceInterfaceData);
Exemple #50
0
		/// <summary>
		/// Helper method to return the device path given a DeviceInterfaceData structure and an InfoSet handle.
		/// Used in 'FindDevice' so check that method out to see how to get an InfoSet handle and a DeviceInterfaceData.
		/// </summary>
		/// <param name="hInfoSet">Handle to the InfoSet</param>
		/// <param name="oInterface">DeviceInterfaceData structure</param>
		/// <returns>The device path or null if there was some problem</returns>
		static string GetDevicePath(IntPtr hInfoSet, ref DeviceInterfaceData oInterface)
		{
			uint nRequiredSize = 0;
			// Get the device interface details
			if (!SetupDiGetDeviceInterfaceDetail(hInfoSet, ref oInterface, IntPtr.Zero, 0, ref nRequiredSize, IntPtr.Zero))
			{
				DeviceInterfaceDetailData oDetail = new DeviceInterfaceDetailData();
				oDetail.Size = 5;	// hardcoded to 5! Sorry, but this works and trying more future proof versions by setting the size to the struct sizeof failed miserably. If you manage to sort it, mail me! Thx
				if (SetupDiGetDeviceInterfaceDetail(hInfoSet, ref oInterface, ref oDetail, nRequiredSize, ref nRequiredSize, IntPtr.Zero))
				{
					return oDetail.DevicePath;
				}
			}
			return null;
		}
Exemple #51
0
		public static List<HIDDevice> FindAllDevice(int nVid, int nPid, Type oType)
		{
			var result = new List<HIDDevice>();
			var addedDevices = new List<string>();

			string strPath = string.Empty;
			string strSearch = string.Format("vid_{0:x4}&pid_{1:x4}", nVid, nPid);
			Guid gHid = HIDGuid;
			IntPtr hInfoSet = SetupDiGetClassDevs(ref gHid, null, IntPtr.Zero, DIGCF_DEVICEINTERFACE | DIGCF_PRESENT);	// this gets a list of all HID devices currently connected to the computer (InfoSet)
			try
			{
				DeviceInterfaceData oInterface = new DeviceInterfaceData();	// build up a device interface data block
				oInterface.Size = Marshal.SizeOf(oInterface);
				// Now iterate through the InfoSet memory block assigned within Windows in the call to SetupDiGetClassDevs
				// to get device details for each device connected
				int nIndex = 0;
				while (SetupDiEnumDeviceInterfaces(hInfoSet, 0, ref gHid, (uint)nIndex, ref oInterface))	// this gets the device interface information for a device at index 'nIndex' in the memory block
				{
					string strDevicePath = GetDevicePath(hInfoSet, ref oInterface);	// get the device path (see helper method 'GetDevicePath')
					if (strDevicePath.IndexOf(strSearch) >= 0)	// do a string search, if we find the VID/PID string then we found our device!
					{
						if (!addedDevices.Contains(strDevicePath))
						{
							addedDevices.Add(strDevicePath);
							//Trace.WriteLine(strDevicePath);

							HIDDevice oNewDevice = (HIDDevice)Activator.CreateInstance(oType);	// create an instance of the class for this device
							oNewDevice.Initialise(strDevicePath);	// initialise it with the device path
							result.Add(oNewDevice);	// and return it
						}
					}
					nIndex++;	// if we get here, we didn't find our device. So move on to the next one.
				}
			}
			catch (Exception ex)
			{
				//throw HIDDeviceException.GenerateError(ex.ToString());
				//Console.WriteLine(ex.ToString());
			}
			finally
			{
				// Before we go, we have to free up the InfoSet memory reserved by SetupDiGetClassDevs
				SetupDiDestroyDeviceInfoList(hInfoSet);
			}
			return result;
		}
Exemple #52
0
 [DllImport("setupapi.dll", SetLastError = true)] protected static extern bool SetupDiGetDeviceInterfaceDetail(IntPtr lpDeviceInfoSet, ref DeviceInterfaceData oInterfaceData, ref DeviceInterfaceDetailData oDetailData, uint nDeviceInterfaceDetailDataSize, ref uint nRequiredSize, IntPtr lpDeviceInfoData);
Exemple #53
0
 public static extern bool SetupDiGetDeviceInterfaceDetail(
     IntPtr lpDeviceInfoSet,
     ref DeviceInterfaceData oInterfaceData,
     ref DeviceInterfaceDetailData oDetailData,  //We have the size -> send struct
     uint nDeviceInterfaceDetailDataSize,
     ref uint nRequiredSize,
     ref DevinfoData deviceInfoData);
Exemple #54
0
		/// <summary>
		/// Helper method to return the device path given a DeviceInterfaceData structure and an InfoSet handle.
		/// Used in 'FindDevice' so check that method out to see how to get an InfoSet handle and a DeviceInterfaceData.
		/// </summary>
		/// <param name="hInfoSet">Handle to the InfoSet</param>
		/// <param name="oInterface">DeviceInterfaceData structure</param>
		/// <returns>The device path or null if there was some problem</returns>
		private static string GetDevicePath(IntPtr hInfoSet, ref DeviceInterfaceData oInterface)
		{
			Int32 nRequiredSize = 0;
            IntPtr detailDataBuffer = IntPtr.Zero;
            
			// Get the device interface details
			if (!SetupDiGetDeviceInterfaceDetail(hInfoSet, ref oInterface, IntPtr.Zero, 0, ref nRequiredSize, IntPtr.Zero))
			{
                //DeviceInterfaceDetailData oDetail = new DeviceInterfaceDetailData();
                //oDetail.Size = (IntPtr.Size == 4) ? (4 + Marshal.SystemDefaultCharSize) : 8;
                detailDataBuffer = Marshal.AllocHGlobal(nRequiredSize);
                Marshal.WriteInt32(detailDataBuffer,(IntPtr.Size == 4)?(4+Marshal.SystemDefaultCharSize):8);

                //DeviceInterfaceDetailData oDetail = new DeviceInterfaceDetailData();
                //oDetail.Size = 5;	// hardcoded to 5! Sorry, but this works and trying more future proof versions by setting the size to the struct sizeof failed miserably. If you manage to sort it, mail me! Thx
                if (SetupDiGetDeviceInterfaceDetail(hInfoSet, ref oInterface,detailDataBuffer , nRequiredSize, ref nRequiredSize, IntPtr.Zero))
				{
                    String devicePathName = "";
                    var pDevicePathName = new IntPtr(detailDataBuffer.ToInt64()+4);
                    devicePathName = Marshal.PtrToStringAuto(pDevicePathName);
                    Marshal.FreeHGlobal(detailDataBuffer);
                    return devicePathName;
                }
			}
			return null;
		}
Exemple #55
0
        private String GetDeviceFilename(int vid, int pid)
        {
            string devname = string.Format("vid_{0:x4}&pid_{1:x4}", vid, pid);
            string filename = null;

            Guid gHid;
            HidD_GetHidGuid(out gHid);

            IntPtr hInfoSet = SetupDiGetClassDevs(ref gHid, null, IntPtr.Zero, DIGCF_DEVICEINTERFACE | DIGCF_PRESENT);

                DeviceInterfaceData oInterface = new DeviceInterfaceData();
                oInterface.Size = Marshal.SizeOf(oInterface);
            int nIndex = 0;
            while (SetupDiEnumDeviceInterfaces(hInfoSet, 0, ref gHid, (uint)nIndex, ref oInterface)) {
            string strDevicePath = GetDevicePath(hInfoSet, ref oInterface);
            System.Console.WriteLine(strDevicePath);
            if (strDevicePath.IndexOf(devname) >= 0){
                filename = strDevicePath;
                break;
            }
            nIndex++;
            }

                SetupDiDestroyDeviceInfoList(hInfoSet);

            return filename;
        }
Exemple #56
0
		public bool SetupDiEnumDeviceInterfaces(
            SafeDeviceInfoSetHandle deviceInfoSet,
            DeviceInfoData deviceInfoData,
            ref Guid interfaceClassGuid,
            uint memberIndex,
            ref DeviceInterfaceData deviceInterfaceData)
			=> SetupDiEnumDeviceInterfaces(deviceInfoSet, deviceInfoData, ref interfaceClassGuid, memberIndex, ref deviceInterfaceData);
Exemple #57
0
 /// <summary>
 /// SetupDiGetDeviceInterfaceDetail
 /// Gets the interface detail from a DeviceInterfaceData. This is pretty much the device path.
 /// You call this twice, once to get the size of the struct you need to send (nDeviceInterfaceDetailDataSize=0)
 /// and once again when you've allocated the required space.
 /// </summary>
 /// <param name="lpDeviceInfoSet">InfoSet to access</param>
 /// <param name="oInterfaceData">DeviceInterfaceData to use</param>
 /// <param name="oDetailData">DeviceInterfaceDetailData to fill with data</param>
 /// <param name="nDeviceInterfaceDetailDataSize">The size of the above</param>
 /// <param name="nRequiredSize">The required size of the above when above is set as zero</param>
 /// <param name="lpDeviceInfoData">Not used</param>
 /// <returns></returns>
 [DllImport("setupapi.dll", SetLastError = true,CharSet =CharSet.Auto)] internal static extern bool SetupDiGetDeviceInterfaceDetail(IntPtr lpDeviceInfoSet, ref DeviceInterfaceData oInterfaceData, IntPtr oDetailData, Int32 nDeviceInterfaceDetailDataSize, ref Int32 nRequiredSize, IntPtr lpDeviceInfoData);
Exemple #58
0
 public static extern bool SetupDiEnumDeviceInterfaces(
   IntPtr handle,
   ref DeviceInfoData deviceInfoData,
   ref Guid guidClass,
   int MemberIndex,
   ref DeviceInterfaceData deviceInterfaceData);
 protected static extern bool SetupDiGetDeviceInterfaceDetail(IntPtr lpDeviceInfoSet, ref DeviceInterfaceData oInterfaceData, ref DeviceInterfaceDetailData oDetailData, uint nDeviceInterfaceDetailDataSize, ref uint nRequiredSize, IntPtr lpDeviceInfoData);
        private static string GetDevicePath(IntPtr hInfoSet, ref DeviceInterfaceData oInterface)
        {
            uint nRequiredSize = 0;
            if (!SetupDiGetDeviceInterfaceDetail(hInfoSet, ref oInterface, IntPtr.Zero, 0, ref nRequiredSize, IntPtr.Zero))
            {
                DeviceInterfaceDetailData oDetail = new DeviceInterfaceDetailData();
                if (Marshal.SizeOf(typeof(IntPtr)) == 8)
                {
                    oDetail.Size = 8;
                }
                else
                {
                    oDetail.Size = 5;
                }

                if (SetupDiGetDeviceInterfaceDetail(hInfoSet, ref oInterface, ref oDetail, nRequiredSize, ref nRequiredSize, IntPtr.Zero))
                {
                    return oDetail.DevicePath;
                }
            }
            return null;
        }