public static extern bool SetupDiGetDeviceInterfaceDetail( IntPtr deviceInfoSet, ref SpDeviceInterfaceData deviceInterfaceData, ref SpDeviceInterfaceDetailData deviceInterfaceDetailData, int deviceInterfaceDetailDataSize, IntPtr unusedRequiredSize, IntPtr unusedDeviceInfoData); // actually struct but optional
internal static extern bool SetupDiGetDeviceInterfaceDetail( IntPtr hFile, ref SpDeviceInterfaceData deviceInterfaceData, [In, Out] byte[] deviceInterfaceDetailData, int deviceInterfaceDetailDataSize, out int requiredSize, IntPtr deviceInfoData);
private static void SetupDiOpenDeviceInterface(IntPtr deviceInfoSet, string devicePath, out SpDeviceInterfaceData deviceInterfaceData) { deviceInterfaceData = new SpDeviceInterfaceData { cbSize = (uint)Marshal.SizeOf(typeof(SpDeviceInterfaceData)) }; if (!SetupDiOpenDeviceInterface(deviceInfoSet, devicePath, 0, ref deviceInterfaceData)) { throw Marshal.GetExceptionForHR(Marshal.GetHRForLastWin32Error()); } }
/// <summary> /// The get device paths. /// </summary> /// <param name="pointer"> /// The pointer. /// </param> /// <param name="oInterface"> /// The o interface. /// </param> /// <returns> /// The <see cref="string"/>. /// </returns> internal static string GetDevicePaths(ref IntPtr pointer, ref SpDeviceInterfaceData oInterface) { uint requiredSize = 0; SetupDiGetDeviceInterfaceDetail(pointer, ref oInterface, IntPtr.Zero, 0, ref requiredSize, IntPtr.Zero); var detail = new DeviceInterfaceDetailData { Size = Marshal.SizeOf(typeof(IntPtr)) == 8 ? 8 : 5 }; SetupDiGetDeviceInterfaceDetail(pointer, ref oInterface, ref detail, requiredSize, ref requiredSize, IntPtr.Zero); return(detail.DevicePath.Clone().ToString()); }
internal static string GetDevicePath(string device) { Main.SendDebug(string.Format("Getting Drive path for Device: {0}", device)); var deviceNumber = GetDeviceNumber(device); var diskGUID = new Guid("53F56307-B6BF-11D0-94F2-00A0C91EFB8B"); var handle = SetupDiGetClassDevs(ref diskGUID, IntPtr.Zero, IntPtr.Zero, (uint)(DIGCF.DIGCFPresent | DIGCF.DIGCFDeviceinterface)); try { if (handle != new IntPtr(-1)) { var success = true; uint i = 0; while (success) { var devinterfacedata = new SpDeviceInterfaceData(); devinterfacedata.cbSize = (uint)Marshal.SizeOf(devinterfacedata); success = SetupDiEnumDeviceInterfaces(handle, IntPtr.Zero, ref diskGUID, i, ref devinterfacedata); if (!success) { continue; } var devinfodata = new SpDevinfoData(); devinfodata.cbSize = (uint)Marshal.SizeOf(devinfodata); var devinterfacedetaildata = new SpDeviceInterfaceDetailData { cbSize = IntPtr.Size == 8 ? 8 : (uint)(4 + Marshal.SystemDefaultCharSize) }; uint nRequiredSize = 0; if (!SetupDiGetDeviceInterfaceDetail(handle, ref devinterfacedata, ref devinterfacedetaildata, 1000, ref nRequiredSize, ref devinfodata)) { SetupDiGetDeviceInterfaceDetail(handle, ref devinterfacedata, ref devinterfacedetaildata, nRequiredSize, ref nRequiredSize, ref devinfodata); } var devnum = GetDeviceNumber(devinterfacedetaildata.DevicePath); if (devnum == deviceNumber) { SetupDiDestroyDeviceInfoList(handle); return(devinterfacedetaildata.DevicePath); } i++; } throw new X360NANDManagerException(X360NANDManagerException.ErrorLevels.NoDeviceFound); } } finally { SetupDiDestroyDeviceInfoList(handle); } throw new Win32Exception(Marshal.GetLastWin32Error()); }
/// <summary> /// Get all Hid devices currently connected to the PC. /// </summary> /// <returns> /// The Enumerable of Hid Devices. /// </returns> internal static IEnumerable <string> GetHidPaths() { HidD_GetHidGuid(out var guid); var hInfoSet = SetupDiGetClassDevs(ref guid, null, IntPtr.Zero, DigitalInterfaces.DeviceInterface | DigitalInterfaces.Present); var data = new SpDeviceInterfaceData { Size = Marshal.SizeOf(typeof(SpDeviceInterfaceData)) }; var index = 0; var paths = new List <string>(); while (SetupDiEnumDeviceInterfaces(hInfoSet, 0, ref guid, index, out data)) { paths.Add(GetDevicePaths(ref hInfoSet, ref data)); index++; } SetupDiDestroyDeviceInfoList(hInfoSet); return(paths); }
internal static string GetDevicePath(string device) { Main.SendDebug(string.Format("Getting Drive path for Device: {0}", device)); var deviceNumber = GetDeviceNumber(device); var diskGUID = new Guid("53F56307-B6BF-11D0-94F2-00A0C91EFB8B"); var handle = SetupDiGetClassDevs(ref diskGUID, IntPtr.Zero, IntPtr.Zero, (uint) (DIGCF.DIGCFPresent | DIGCF.DIGCFDeviceinterface)); try { if(handle != new IntPtr(-1)) { var success = true; uint i = 0; while(success) { var devinterfacedata = new SpDeviceInterfaceData(); devinterfacedata.cbSize = (uint) Marshal.SizeOf(devinterfacedata); success = SetupDiEnumDeviceInterfaces(handle, IntPtr.Zero, ref diskGUID, i, ref devinterfacedata); if(!success) continue; var devinfodata = new SpDevinfoData(); devinfodata.cbSize = (uint) Marshal.SizeOf(devinfodata); var devinterfacedetaildata = new SpDeviceInterfaceDetailData { cbSize = IntPtr.Size == 8 ? 8 : (uint) (4 + Marshal.SystemDefaultCharSize) }; uint nRequiredSize = 0; if(!SetupDiGetDeviceInterfaceDetail(handle, ref devinterfacedata, ref devinterfacedetaildata, 1000, ref nRequiredSize, ref devinfodata)) SetupDiGetDeviceInterfaceDetail(handle, ref devinterfacedata, ref devinterfacedetaildata, nRequiredSize, ref nRequiredSize, ref devinfodata); var devnum = GetDeviceNumber(devinterfacedetaildata.DevicePath); if(devnum == deviceNumber) { SetupDiDestroyDeviceInfoList(handle); return devinterfacedetaildata.DevicePath; } i++; } throw new X360NANDManagerException(X360NANDManagerException.ErrorLevels.NoDeviceFound); } } finally { SetupDiDestroyDeviceInfoList(handle); } throw new Win32Exception(Marshal.GetLastWin32Error()); }
internal static extern bool SetupDiGetDeviceInterfaceDetail(IntPtr deviceInfoSet, ref SpDeviceInterfaceData deviceInterfaceData, ref SpDeviceInterfaceDetailData deviceInterfaceDetailData, int deviceInterfaceDetailDataSize, ref int requiredSize, ref SpDevinfoData deviceInfoData);
[DllImport("setupapi.dll", CharSet = CharSet.Auto, SetLastError = true)] private static extern Boolean SetupDiEnumDeviceInterfaces(IntPtr hDevInfo, IntPtr devInfo, ref Guid interfaceClassGuid, UInt32 memberIndex, ref SpDeviceInterfaceData deviceInterfaceData);
public static extern bool SetupDiEnumDeviceInterfaces(IntPtr deviceInfoSet, IntPtr deviceInfoData, ref Guid hidGuid, int memberIndex, ref SpDeviceInterfaceData deviceInterfaceData);
internal static extern bool SetupDiEnumDeviceInterfaces(SafeHandle hDevInfo, IntPtr devInfo, ref Guid interfaceClassGuid, [MarshalAs(UnmanagedType.U4)] uint memberIndex, ref SpDeviceInterfaceData deviceInterfaceData);
internal static extern bool SetupDiEnumDeviceInterfaces(IntPtr deviceInfoSet, ref SpDevinfoData deviceInfoData, ref Guid interfaceClassGuid, int memberIndex, ref SpDeviceInterfaceData deviceInterfaceData);
public static extern bool SetupDiEnumDeviceInterfaces( IntPtr deviceInfoSet, IntPtr deviceInfoData, // actually struct but optional ref Guid interfaceClassGuid, int memberIndex, ref SpDeviceInterfaceData deviceInterfaceData);
internal static extern Boolean SetupDiEnumDeviceInterfaces(IntPtr deviceInfoSet, IntPtr deviceInfoData, ref Guid interfaceClassGuid, Int32 memberIndex, ref SpDeviceInterfaceData deviceInterfaceData);
/// <summary> /// Use SetupDi API functions to retrieve the device path name of an /// attached device that belongs to a device interface class. /// </summary> /// /// <param name="myGuid"> an interface class GUID. </param> /// <param name="devicePathName"> a pointer to the device path name /// of an attached device. </param> /// /// <returns> /// True if a device is found, False if not. /// </returns> internal Boolean FindDeviceFromGuid(Guid myGuid, ref String devicePathName) { var bufferSize = 0; var detailDataBuffer = IntPtr.Zero; var deviceInfoSet = new IntPtr(); var lastDevice = false; var myDeviceInterfaceData = new SpDeviceInterfaceData(); try { // *** API function // summary // Retrieves a device information set for a specified group of devices. // SetupDiEnumDeviceInterfaces uses the device information set. // parameters // Interface class GUID. // Null to retrieve information for all device instances. // Optional handle to a top-level window (unused here). // Flags to limit the returned information to currently present devices // and devices that expose interfaces in the class specified by the GUID. // Returns // Handle to a device information set for the devices. deviceInfoSet = SetupDiGetClassDevs(ref myGuid, IntPtr.Zero, IntPtr.Zero, DigcfPresent | DigcfDeviceinterface); var deviceFound = false; var memberIndex = 0; // The cbSize element of the MyDeviceInterfaceData structure must be set to // the structure's size in bytes. // The size is 28 bytes for 32-bit code and 32 bits for 64-bit code. myDeviceInterfaceData.CbSize = Marshal.SizeOf(myDeviceInterfaceData); do { // Begin with 0 and increment through the device information set until // no more devices are available. // *** API function // summary // Retrieves a handle to a SP_DEVICE_INTERFACE_DATA structure for a device. // On return, MyDeviceInterfaceData contains the handle to a // SP_DEVICE_INTERFACE_DATA structure for a detected device. // parameters // DeviceInfoSet returned by SetupDiGetClassDevs. // Optional SP_DEVINFO_DATA structure that defines a device instance // that is a member of a device information set. // Device interface GUID. // Index to specify a device in a device information set. // Pointer to a handle to a SP_DEVICE_INTERFACE_DATA structure for a device. // Returns True on success. var success = SetupDiEnumDeviceInterfaces (deviceInfoSet, IntPtr.Zero, ref myGuid, memberIndex, ref myDeviceInterfaceData); // Find out if a device information set was retrieved. if (!success) { lastDevice = true; } else { // A device is present. // *** API function: // summary: // Retrieves an SP_DEVICE_INTERFACE_DETAIL_DATA structure // containing information about a device. // To retrieve the information, call this function twice. // The first time returns the size of the structure. // The second time returns a pointer to the data. // parameters // DeviceInfoSet returned by SetupDiGetClassDevs // SP_DEVICE_INTERFACE_DATA structure returned by SetupDiEnumDeviceInterfaces // A returned pointer to an SP_DEVICE_INTERFACE_DETAIL_DATA // Structure to receive information about the specified interface. // The size of the SP_DEVICE_INTERFACE_DETAIL_DATA structure. // Pointer to a variable that will receive the returned required size of the // SP_DEVICE_INTERFACE_DETAIL_DATA structure. // Returned pointer to an SP_DEVINFO_DATA structure to receive information about the device. // Returns True on success. SetupDiGetDeviceInterfaceDetail (deviceInfoSet, ref myDeviceInterfaceData, IntPtr.Zero, 0, ref bufferSize, IntPtr.Zero); // Allocate memory for the SP_DEVICE_INTERFACE_DETAIL_DATA structure using the returned buffer size. detailDataBuffer = Marshal.AllocHGlobal(bufferSize); // Store cbSize in the first bytes of the array. The number of bytes varies with 32- and 64-bit systems. Marshal.WriteInt32(detailDataBuffer, (IntPtr.Size == 4) ? (4 + Marshal.SystemDefaultCharSize) : 8); // Call SetupDiGetDeviceInterfaceDetail again. // This time, pass a pointer to DetailDataBuffer // and the returned required buffer size. SetupDiGetDeviceInterfaceDetail (deviceInfoSet, ref myDeviceInterfaceData, detailDataBuffer, bufferSize, ref bufferSize, IntPtr.Zero); // Skip over cbsize (4 bytes) to get the address of the devicePathName. var pDevicePathName = new IntPtr(detailDataBuffer.ToInt32() + 4); // Get the String containing the devicePathName. devicePathName = Marshal.PtrToStringAuto(pDevicePathName); deviceFound = true; } memberIndex = memberIndex + 1; }while (lastDevice != true); return(deviceFound); } finally { if (detailDataBuffer != IntPtr.Zero) { // Free the memory allocated previously by AllocHGlobal. Marshal.FreeHGlobal(detailDataBuffer); } if (deviceInfoSet != IntPtr.Zero) { // *** API function // summary // Frees the memory reserved for the DeviceInfoSet returned by SetupDiGetClassDevs. // parameters // DeviceInfoSet returned by SetupDiGetClassDevs. // returns True on success. SetupDiDestroyDeviceInfoList(deviceInfoSet); } } }
internal static extern Boolean SetupDiGetDeviceInterfaceDetail(IntPtr deviceInfoSet, ref SpDeviceInterfaceData deviceInterfaceData, IntPtr deviceInterfaceDetailData, Int32 deviceInterfaceDetailDataSize, ref Int32 requiredSize, IntPtr deviceInfoData);
private static extern bool SetupDiDeleteDeviceInterfaceData(IntPtr deviceInfoSet, [In] ref SpDeviceInterfaceData deviceInterfaceData);
private static extern bool SetupDiOpenDeviceInterface(IntPtr deviceInfoSet, string devicePath, uint openFlags, ref SpDeviceInterfaceData deviceInterfaceData);
public static UsbDevice FindDriveLetter(string driveName) { UsbDevice foundDevice = null; var instanceID = string.Empty; var devNum = UsbLogic.GetDeviceNumber($@"\\.\{driveName.TrimEnd('\\')}"); if (devNum < default(int)) { return(foundDevice); } var diskGUID = new Guid(UsbConstants.GUID_DEVINTERFACE_DISK); var h = SetupApi.SetupDiGetClassDevs(ref diskGUID, default(int), IntPtr.Zero, UsbConstants.DIGCF_PRESENT | UsbConstants.DIGCF_DEVICEINTERFACE); if (h.ToInt32() != UsbConstants.INVALID_HANDLE_VALUE) { var i = default(int); var success = true; do { var dia = new SpDeviceInterfaceData(); dia.cbSize = Marshal.SizeOf(dia); success = SetupApi.SetupDiEnumDeviceInterfaces(h, IntPtr.Zero, ref diskGUID, i, ref dia); if (success) { var da = new SpDevinfoData(); da.cbSize = Marshal.SizeOf(da); var didd = new SpDeviceInterfaceDetailData { cbSize = 4 + Marshal.SystemDefaultCharSize, }; var nRequiredSize = default(int); int nBytes = UsbConstants.BUFFER_SIZE; if (SetupApi.SetupDiGetDeviceInterfaceDetail(h, ref dia, ref didd, nBytes, ref nRequiredSize, ref da)) { if (UsbLogic.GetDeviceNumber(didd.DevicePath) == devNum) { SetupApi.CM_Get_Parent(out IntPtr ptrPrevious, da.DevInst, default(int)); var ptrInstanceBuf = Marshal.AllocHGlobal(nBytes); SetupApi.CM_Get_Device_ID(ptrPrevious, ptrInstanceBuf, nBytes, default(int)); instanceID = Marshal.PtrToStringAuto(ptrInstanceBuf); Marshal.FreeHGlobal(ptrInstanceBuf); break; } } } i++; } while (success); SetupApi.SetupDiDestroyDeviceInfoList(h); } if (instanceID.StartsWith("USB\\")) { foundDevice = UsbLogic.FindDeviceByInstanceID(instanceID, driveName); } return(foundDevice); }
public static extern bool SetupDiEnumDeviceInterfaces(IntPtr deviceInfoSet, SpDevInfoData deviceInfoData, ref Guid interfaceClassGuid, uint memberIndex, SpDeviceInterfaceData deviceInterfaceData);
public static extern bool SetupDiGetDeviceInterfaceDetail( IntPtr deviceInfoSet, ref SpDeviceInterfaceData deviceInterfaceData, ref SpDeviceInterfaceDetailData deviceInterfaceDetailData, int deviceInterfaceDetailDataSize, IntPtr unusedRequiredSize, IntPtr unusedDeviceInfoData);
public static extern Boolean SetupDiGetDeviceInterfaceDetail( IntPtr hDevInfo, ref SpDeviceInterfaceData deviceInterfaceData, ref SpDeviceInterfaceDetailData deviceInterfaceDetailData, UInt32 deviceInterfaceDetailDataSize, out UInt32 requiredSize, ref SpDevinfoData deviceInfoData );
public static IEnumerable <UsbController> GetControllers() { var hostGUID = new Guid(UsbConstants.GUID_DEVINTERFACE_HUBCONTROLLER); var h = SetupApi.SetupDiGetClassDevs(ref hostGUID, default(int), IntPtr.Zero, UsbConstants.DIGCF_PRESENT | UsbConstants.DIGCF_DEVICEINTERFACE); if (h.ToInt32() != UsbConstants.INVALID_HANDLE_VALUE) { var ptrBuf = Marshal.AllocHGlobal(UsbConstants.BUFFER_SIZE); var i = default(int); var success = default(bool); do { var host = new UsbController(null) { ControllerIndex = i, }; var dia = new SpDeviceInterfaceData(); dia.cbSize = Marshal.SizeOf(dia); success = SetupApi.SetupDiEnumDeviceInterfaces(h, IntPtr.Zero, ref hostGUID, i, ref dia); if (success) { var da = new SpDevinfoData(); da.cbSize = Marshal.SizeOf(da); var didd = new SpDeviceInterfaceDetailData { cbSize = 4 + Marshal.SystemDefaultCharSize, }; var nRequiredSize = default(int); var nBytes = UsbConstants.BUFFER_SIZE; if (SetupApi.SetupDiGetDeviceInterfaceDetail(h, ref dia, ref didd, nBytes, ref nRequiredSize, ref da)) { host.ControllerDevicePath = didd.DevicePath; var requiredSize = default(int); var regType = UsbConstants.REG_SZ; if (SetupApi.SetupDiGetDeviceRegistryProperty(h, ref da, UsbConstants.SPDRP_DEVICEDESC, ref regType, ptrBuf, UsbConstants.BUFFER_SIZE, ref requiredSize)) { host.ControllerDeviceDesc = Marshal.PtrToStringAuto(ptrBuf); } if (SetupApi.SetupDiGetDeviceRegistryProperty(h, ref da, UsbConstants.SPDRP_DRIVER, ref regType, ptrBuf, UsbConstants.BUFFER_SIZE, ref requiredSize)) { host.ControllerDriverKeyName = Marshal.PtrToStringAuto(ptrBuf); } } yield return(host); } i++; }while (success); Marshal.FreeHGlobal(ptrBuf); SetupApi.SetupDiDestroyDeviceInfoList(h); } }
internal static extern bool SetupDiGetDeviceInterfaceDetailBuffer(IntPtr deviceInfoSet, ref SpDeviceInterfaceData deviceInterfaceData, IntPtr deviceInterfaceDetailData, int deviceInterfaceDetailDataSize, ref int requiredSize, IntPtr deviceInfoData);
public static extern bool SetupDiEnumDeviceInterfaces([In] IntPtr deviceInfoSet, [In, Optional] IntPtr deviceInfoData, [In, Out] ref Guid interfaceClassGuid, [In] int memberIndex, [In, Out] ref SpDeviceInterfaceData deviceInterfaceData);
/// <summary> /// Use SetupDi API functions to retrieve the device path name of an /// attached device that belongs to a device interface class. /// </summary> /// /// <param name="myGuid"> an interface class GUID. </param> /// <param name="devicePathName"> a pointer to the device path name /// of an attached device. </param> /// /// <returns> /// True if a device is found, False if not. /// </returns> internal Boolean FindDeviceFromGuid(Guid myGuid, ref String devicePathName) { var bufferSize = 0; var detailDataBuffer = IntPtr.Zero; var deviceInfoSet = new IntPtr(); var lastDevice = false; var myDeviceInterfaceData = new SpDeviceInterfaceData(); try { // *** API function // summary // Retrieves a device information set for a specified group of devices. // SetupDiEnumDeviceInterfaces uses the device information set. // parameters // Interface class GUID. // Null to retrieve information for all device instances. // Optional handle to a top-level window (unused here). // Flags to limit the returned information to currently present devices // and devices that expose interfaces in the class specified by the GUID. // Returns // Handle to a device information set for the devices. deviceInfoSet = SetupDiGetClassDevs(ref myGuid, IntPtr.Zero, IntPtr.Zero, DigcfPresent | DigcfDeviceinterface); var deviceFound = false; var memberIndex = 0; // The cbSize element of the MyDeviceInterfaceData structure must be set to // the structure's size in bytes. // The size is 28 bytes for 32-bit code and 32 bits for 64-bit code. myDeviceInterfaceData.CbSize = Marshal.SizeOf(myDeviceInterfaceData); do { // Begin with 0 and increment through the device information set until // no more devices are available. // *** API function // summary // Retrieves a handle to a SP_DEVICE_INTERFACE_DATA structure for a device. // On return, MyDeviceInterfaceData contains the handle to a // SP_DEVICE_INTERFACE_DATA structure for a detected device. // parameters // DeviceInfoSet returned by SetupDiGetClassDevs. // Optional SP_DEVINFO_DATA structure that defines a device instance // that is a member of a device information set. // Device interface GUID. // Index to specify a device in a device information set. // Pointer to a handle to a SP_DEVICE_INTERFACE_DATA structure for a device. // Returns True on success. var success = SetupDiEnumDeviceInterfaces (deviceInfoSet, IntPtr.Zero, ref myGuid, memberIndex, ref myDeviceInterfaceData); // Find out if a device information set was retrieved. if (!success) lastDevice = true; else { // A device is present. // *** API function: // summary: // Retrieves an SP_DEVICE_INTERFACE_DETAIL_DATA structure // containing information about a device. // To retrieve the information, call this function twice. // The first time returns the size of the structure. // The second time returns a pointer to the data. // parameters // DeviceInfoSet returned by SetupDiGetClassDevs // SP_DEVICE_INTERFACE_DATA structure returned by SetupDiEnumDeviceInterfaces // A returned pointer to an SP_DEVICE_INTERFACE_DETAIL_DATA // Structure to receive information about the specified interface. // The size of the SP_DEVICE_INTERFACE_DETAIL_DATA structure. // Pointer to a variable that will receive the returned required size of the // SP_DEVICE_INTERFACE_DETAIL_DATA structure. // Returned pointer to an SP_DEVINFO_DATA structure to receive information about the device. // Returns True on success. SetupDiGetDeviceInterfaceDetail (deviceInfoSet, ref myDeviceInterfaceData, IntPtr.Zero, 0, ref bufferSize, IntPtr.Zero); // Allocate memory for the SP_DEVICE_INTERFACE_DETAIL_DATA structure using the returned buffer size. detailDataBuffer = Marshal.AllocHGlobal(bufferSize); // Store cbSize in the first bytes of the array. The number of bytes varies with 32- and 64-bit systems. Marshal.WriteInt32(detailDataBuffer, (IntPtr.Size == 4) ? (4 + Marshal.SystemDefaultCharSize) : 8); // Call SetupDiGetDeviceInterfaceDetail again. // This time, pass a pointer to DetailDataBuffer // and the returned required buffer size. SetupDiGetDeviceInterfaceDetail (deviceInfoSet, ref myDeviceInterfaceData, detailDataBuffer, bufferSize, ref bufferSize, IntPtr.Zero); // Skip over cbsize (4 bytes) to get the address of the devicePathName. var pDevicePathName = new IntPtr(detailDataBuffer.ToInt32() + 4); // Get the String containing the devicePathName. devicePathName = Marshal.PtrToStringAuto(pDevicePathName); deviceFound = true; } memberIndex = memberIndex + 1; } while (lastDevice != true); return deviceFound; } finally { if (detailDataBuffer != IntPtr.Zero) { // Free the memory allocated previously by AllocHGlobal. Marshal.FreeHGlobal(detailDataBuffer); } if (deviceInfoSet != IntPtr.Zero) { // *** API function // summary // Frees the memory reserved for the DeviceInfoSet returned by SetupDiGetClassDevs. // parameters // DeviceInfoSet returned by SetupDiGetClassDevs. // returns True on success. SetupDiDestroyDeviceInfoList(deviceInfoSet); } } }
public static extern bool SetupDiGetDeviceInterfaceDetail([In] IntPtr deviceInfoSet, [In, Out] ref SpDeviceInterfaceData deviceInterfaceData, [In, Out] IntPtr deviceInterfaceDetailData, [In] int deviceInterfaceDetailDataSize, [In, Out] ref int requiredSize, [In] IntPtr deviceInfoData);
public static bool FindHidDevices(ref string[] listOfDevicePathNames, ref int numberOfDevicesFound) { TmoShare.WriteLog("DeviceDiscovery:findHidDevices() -> 开始查找所有HID设备"); // Initialise the internal variables required for performing the search var bufferSize = 0; var detailDataBuffer = IntPtr.Zero; bool deviceFound; var deviceInfoSet = new IntPtr(); var lastDevice = false; int listIndex; var deviceInterfaceData = new SpDeviceInterfaceData(); // Get the required GUID var systemHidGuid = new Guid(); Hid.HidD_GetHidGuid(ref systemHidGuid); TmoShare.WriteLog(string.Format("DeviceDiscovery:findHidDevices() -> 找到HID设备全局 GUID {0}", systemHidGuid)); try { // Here we populate a list of plugged-in devices matching our class GUID (DIGCF_PRESENT specifies that the list // should only contain devices which are plugged in) TmoShare.WriteLog("DeviceDiscovery:findHidDevices() -> 获取所有HID设备句柄"); deviceInfoSet = SetupApi.SetupDiGetClassDevs(ref systemHidGuid, IntPtr.Zero, IntPtr.Zero, Constants.DigcfPresent | Constants.DigcfDeviceinterface); // Reset the deviceFound flag and the memberIndex counter deviceFound = false; listIndex = 0; deviceInterfaceData.cbSize = Marshal.SizeOf(deviceInterfaceData); // Look through the retrieved list of class GUIDs looking for a match on our interface GUID do { TmoShare.WriteLog("DeviceDiscovery:findHidDevices() -> 获取设备信息"); var success = SetupApi.SetupDiEnumDeviceInterfaces(deviceInfoSet, IntPtr.Zero, ref systemHidGuid, listIndex, ref deviceInterfaceData); if (!success) { TmoShare.WriteLog("DeviceDiscovery:findHidDevices() -> 已经找到最后一个-停止"); lastDevice = true; } else { // The target device has been found, now we need to retrieve the device path so we can open // the read and write handles required for USB communication // First call is just to get the required buffer size for the real request SetupApi.SetupDiGetDeviceInterfaceDetail (deviceInfoSet, ref deviceInterfaceData, IntPtr.Zero, 0, ref bufferSize, IntPtr.Zero); // Allocate some memory for the buffer detailDataBuffer = Marshal.AllocHGlobal(bufferSize); Marshal.WriteInt32(detailDataBuffer, (IntPtr.Size == 4) ? (4 + Marshal.SystemDefaultCharSize) : 8); // Second call gets the detailed data buffer TmoShare.WriteLog("DeviceDiscovery:findHidDevices() -> 获取设备详细信息"); SetupApi.SetupDiGetDeviceInterfaceDetail (deviceInfoSet, ref deviceInterfaceData, detailDataBuffer, bufferSize, ref bufferSize, IntPtr.Zero); // Skip over cbsize (4 bytes) to get the address of the devicePathName. var pDevicePathName = new IntPtr(detailDataBuffer.ToInt32() + 4); // Get the String containing the devicePathName. listOfDevicePathNames[listIndex] = Marshal.PtrToStringAuto(pDevicePathName).ToUpper(); TmoShare.WriteLog(string.Format("DeviceDiscovery:findHidDevices() -> 将找到的设备添加进列表 (索引 {0})", listIndex)); deviceFound = true; listIndex++; } }while (lastDevice != true); } catch (Exception ex) { // Something went badly wrong... output some debug and return false to indicated device discovery failure TmoShare.WriteLog("DeviceDiscovery:findHidDevices() -> 发生异常: " + ex.Message); return(false); } finally { // Clean up the unmanaged memory allocations if (detailDataBuffer != IntPtr.Zero) { // Free the memory allocated previously by AllocHGlobal. Marshal.FreeHGlobal(detailDataBuffer); } if (deviceInfoSet != IntPtr.Zero) { SetupApi.SetupDiDestroyDeviceInfoList(deviceInfoSet); } } if (deviceFound) { TmoShare.WriteLog(String.Format("DeviceDiscovery:findHidDevices() -> 一共找到{0}个HID设备", listIndex)); numberOfDevicesFound = listIndex; } else { TmoShare.WriteLog("DeviceDiscovery:findHidDevices() -> 没有找到HID设备"); } return(deviceFound); }
internal static extern bool SetupDiGetDeviceInterfaceDetail(IntPtr lpDeviceInfoSet, ref SpDeviceInterfaceData interfaceData, ref SpDeviceInterfaceDetailDataWithPath detailData, uint nDeviceInterfaceDetailDataSize, IntPtr nRequiredSize, IntPtr lpDeviceInfoData);
internal static extern bool SetupDiGetDeviceInterfaceDetail(SafeHandle hDevInfo, ref SpDeviceInterfaceData deviceInterfaceData, ref SpDeviceInterfaceDetailData deviceInterfaceDetailData, [MarshalAs(UnmanagedType.U4)] uint deviceInterfaceDetailDataSize, IntPtr requiredSize, ref SpDeviceInfoData deviceInfoData);
/// <summary> /// Find a device based upon a Device Number /// </summary> /// <param name="devNum">Device Number</param> /// <param name="deviceGuid">Device GUID</param> /// <returns>USB device</returns> static UsbDevice FindDeviceNumber(int devNum, string deviceGuid) { UsbDevice foundDevice = null; string instanceId = ""; Guid diskGuid = new Guid(deviceGuid); // We start at the "root" of the device tree and look for all // devices that match the interface GUID of a disk IntPtr h = SetupDiGetClassDevs(ref diskGuid, 0, IntPtr.Zero, DIGCF_PRESENT | DIGCF_DEVICEINTERFACE); if (h.ToInt32() != INVALID_HANDLE_VALUE) { bool success; int i = 0; do { // create a Device Interface Data structure SpDeviceInterfaceData dia = new SpDeviceInterfaceData(); dia.cbSize = Marshal.SizeOf(dia); // start the enumeration success = SetupDiEnumDeviceInterfaces(h, IntPtr.Zero, ref diskGuid, i, ref dia); if (success) { // build a DevInfo Data structure SpDevinfoData da = new SpDevinfoData(); da.cbSize = Marshal.SizeOf(da); // build a Device Interface Detail Data structure SpDeviceInterfaceDetailData didd = new SpDeviceInterfaceDetailData { cbSize = 4 + Marshal.SystemDefaultCharSize }; // trust me :) // now we can get some more detailed information int nRequiredSize = 0; const int N_BYTES = BUFFER_SIZE; if (SetupDiGetDeviceInterfaceDetail(h, ref dia, ref didd, N_BYTES, ref nRequiredSize, ref da)) { if (GetDeviceNumber(didd.DevicePath) == devNum) { // current InstanceID is at the "USBSTOR" level, so we // need up "move up" one level to get to the "USB" level CM_Get_Parent(out IntPtr ptrPrevious, da.DevInst, 0); // Now we get the InstanceID of the USB level device IntPtr ptrInstanceBuf = Marshal.AllocHGlobal(N_BYTES); CM_Get_Device_ID(ptrPrevious, ptrInstanceBuf, N_BYTES, 0); instanceId = Marshal.PtrToStringAuto(ptrInstanceBuf); Marshal.FreeHGlobal(ptrInstanceBuf); System.Console.WriteLine("InstanceId: {0}", instanceId); //break; } } } i++; }while(success); SetupDiDestroyDeviceInfoList(h); } // Did we find an InterfaceID of a USB device? if (instanceId?.StartsWith("USB\\", StringComparison.Ordinal) == true) { foundDevice = FindDeviceByInstanceId(instanceId); } return(foundDevice); }
/// <summary>Return a list of USB Host Controllers</summary> /// <returns>List of USB Host Controllers</returns> static IEnumerable <UsbController> GetHostControllers() { List <UsbController> hostList = new List <UsbController>(); var hostGuid = new Guid(GUID_DEVINTERFACE_HUBCONTROLLER); // We start at the "root" of the device tree and look for all // devices that match the interface GUID of a Hub Controller IntPtr h = SetupDiGetClassDevs(ref hostGuid, 0, IntPtr.Zero, DIGCF_PRESENT | DIGCF_DEVICEINTERFACE); if (h == INVALID_HANDLE_VALUE) { return(new ReadOnlyCollection <UsbController>(hostList)); } IntPtr ptrBuf = Marshal.AllocHGlobal(BUFFER_SIZE); bool success; int i = 0; do { var host = new UsbController { ControllerIndex = i }; // create a Device Interface Data structure var dia = new SpDeviceInterfaceData(); dia.cbSize = Marshal.SizeOf(dia); // start the enumeration success = SetupDiEnumDeviceInterfaces(h, IntPtr.Zero, ref hostGuid, i, ref dia); if (success) { // build a DevInfo Data structure var da = new SpDevinfoData(); da.cbSize = Marshal.SizeOf(da); // build a Device Interface Detail Data structure var didd = new SpDeviceInterfaceDetailData { cbSize = 4 + Marshal.SystemDefaultCharSize }; // trust me :) // now we can get some more detailed information int nRequiredSize = 0; const int N_BYTES = BUFFER_SIZE; if (SetupDiGetDeviceInterfaceDetail(h, ref dia, ref didd, N_BYTES, ref nRequiredSize, ref da)) { host.ControllerDevicePath = didd.DevicePath; // get the Device Description and DriverKeyName int requiredSize = 0; int regType = REG_SZ; if (SetupDiGetDeviceRegistryProperty(h, ref da, SPDRP_DEVICEDESC, ref regType, ptrBuf, BUFFER_SIZE, ref requiredSize)) { host.ControllerDeviceDesc = Marshal.PtrToStringAuto(ptrBuf); } if (SetupDiGetDeviceRegistryProperty(h, ref da, SPDRP_DRIVER, ref regType, ptrBuf, BUFFER_SIZE, ref requiredSize)) { host.ControllerDriverKeyName = Marshal.PtrToStringAuto(ptrBuf); } } hostList.Add(host); } i++; } while(success); Marshal.FreeHGlobal(ptrBuf); SetupDiDestroyDeviceInfoList(h); // convert it into a Collection return(new ReadOnlyCollection <UsbController>(hostList)); }
internal static extern bool SetupDiEnumDeviceInterfaces(IntPtr lpDeviceInfoSet, ref SpDeviInfoData deviceInfoData, ref Guid gClass, uint nIndex, ref SpDeviceInterfaceData interfaceData);
[DllImport("setupapi.dll", CharSet = CharSet.Auto, SetLastError = true)] private static extern Boolean SetupDiGetDeviceInterfaceDetail(IntPtr hDevInfo, ref SpDeviceInterfaceData deviceInterfaceData, ref SpDeviceInterfaceDetailData deviceInterfaceDetailData, UInt32 deviceInterfaceDetailDataSize, ref UInt32 requiredSize, ref SpDevinfoData deviceInfoData);
public static List <string> FindAllHidDevices() { var listOfDevicePathNames = new List <string>(); var detailDataBuffer = IntPtr.Zero; int listIndex = 0; var deviceInterfaceData = new SpDeviceInterfaceData(); int lasterror = 0; // Get the required HID class GUID var systemHidGuid = new Guid(); Hid.HidD_GetHidGuid(ref systemHidGuid); IntPtr deviceInfoSet = SetupDiGetClassDevs(ref systemHidGuid); deviceInterfaceData.cbSize = Marshal.SizeOf(deviceInterfaceData); try { // Look through the retrieved list of class GUIDs looking for a match on our interface GUID // SetupDiEnumDeviceInterfaces will return false if it fails for any reason, including when no more items are left // so we need to keep looping until the last thrown error is ERROR_NO_MORE_ITEMS // Note: we post increment lastIndex so each subsequent call refers to a new device while (SetupApi.SetupDiEnumDeviceInterfaces(deviceInfoSet, IntPtr.Zero, ref systemHidGuid, listIndex++, ref deviceInterfaceData) || (lasterror = Marshal.GetLastWin32Error()) != Constants.ERROR_NO_MORE_ITEMS) { if (lasterror != 0) { // SetupDiEnumDeviceInterfaces failed and it wasn't ERROR_NO_MORE_ITEMS as this would have stopped the loop Debug.WriteLine("SetupDiEnumDeviceInterfaces failed for run {0} with error {1}", listIndex, lasterror); continue; } int bufferSize = 0; // The target device has been found, now we need to retrieve the device path so we can open // the read and write handles required for USB communication // First call fails with ERROR_INSUFFICIENT_BUFFER and is used just to get the required buffer size for the real request var success = SetupApi.SetupDiGetDeviceInterfaceDetail( deviceInfoSet, ref deviceInterfaceData, IntPtr.Zero, 0, ref bufferSize, IntPtr.Zero ); // Allocate some memory for the buffer detailDataBuffer = Marshal.AllocHGlobal(bufferSize); Marshal.WriteInt32(detailDataBuffer, (IntPtr.Size == 4) ? (4 + Marshal.SystemDefaultCharSize) : 8); // Second call gets the detailed data buffer success = SetupApi.SetupDiGetDeviceInterfaceDetail( deviceInfoSet, ref deviceInterfaceData, detailDataBuffer, bufferSize, ref bufferSize, IntPtr.Zero ); if (!success) { Debug.WriteLine("SetupDiGetDeviceInterfaceDetail failed for run {0} with error {1}", listIndex, Marshal.GetLastWin32Error()); continue; } // Skip over cbsize (4 bytes) to get the address of the devicePathName. var pDevicePathName = IntPtr.Add(detailDataBuffer, 4); // Get the String containing the devicePathName. listOfDevicePathNames.Add(Marshal.PtrToStringAuto(pDevicePathName)); } } catch (Exception) { // Something went badly wrong... listOfDevicePathNames.Clear(); } finally { // Clean up the unmanaged memory allocations and free resources held by the windows API Marshal.FreeHGlobal(detailDataBuffer); SetupApi.SetupDiDestroyDeviceInfoList(deviceInfoSet); } return(listOfDevicePathNames); }
public static extern bool SetupDiGetDeviceInterfaceDetail(IntPtr deviceInfoSet, SpDeviceInterfaceData deviceInterfaceData, ref SpDeviceInterfaceDetailData deviceInterfaceDetailData, int deviceInterfaceDetailDataSize, ref int requiredSize, IntPtr unusedDeviceInfoData);
public static extern Boolean SetupDiEnumDeviceInterfaces( IntPtr hDevInfo, IntPtr devInfo, ref Guid interfaceClassGuid, UInt32 memberIndex, ref SpDeviceInterfaceData deviceInterfaceData );
public static bool FindHidDevices(ref List <string> DevicePathNames) { Debug.WriteLine("findHidDevices() -> Method called"); // Initialize the internal variables required for performing the search var bufferSize = 0; var detailDataBuffer = IntPtr.Zero; bool deviceFound; var deviceInfoSet = new IntPtr(); var lastDevice = false; int listIndex; var deviceInterfaceData = new SpDeviceInterfaceData(); // Get the required GUID var systemHidGuid = new Guid(); Hid.HidD_GetHidGuid(ref systemHidGuid); Debug.WriteLine(string.Format("findHidDevices() -> Fetched GUID for HID devices ({0})", systemHidGuid.ToString())); try { // Here we populate a list of plugged-in devices matching our class GUID (DIGCF_PRESENT specifies that the list // should only contain devices which are plugged in) Debug.WriteLine("findHidDevices() -> Using SetupDiGetClassDevs to get all devices with the correct GUID"); deviceInfoSet = SetupApi.SetupDiGetClassDevs(ref systemHidGuid, IntPtr.Zero, IntPtr.Zero, Constants.DigcfPresent | Constants.DigcfDeviceinterface); // Reset the deviceFound flag and the memberIndex counter deviceFound = false; listIndex = 0; deviceInterfaceData.cbSize = Marshal.SizeOf(deviceInterfaceData); // Look through the retrieved list of class GUIDs looking for a match on our interface GUID do { //Debug.WriteLine("usbGenericHidCommunication:findHidDevices() -> Enumerating devices"); var success = SetupApi.SetupDiEnumDeviceInterfaces(deviceInfoSet, IntPtr.Zero, ref systemHidGuid, listIndex, ref deviceInterfaceData); if (!success) { //Debug.WriteLine("usbGenericHidCommunication:findHidDevices() -> No more devices left - giving up"); lastDevice = true; } else { // The target device has been found, now we need to retrieve the device path so we can open // the read and write handles required for USB communication // First call is just to get the required buffer size for the real request SetupApi.SetupDiGetDeviceInterfaceDetail (deviceInfoSet, ref deviceInterfaceData, IntPtr.Zero, 0, ref bufferSize, IntPtr.Zero); // Allocate some memory for the buffer detailDataBuffer = Marshal.AllocHGlobal(bufferSize); Marshal.WriteInt32(detailDataBuffer, (IntPtr.Size == 4) ? (4 + Marshal.SystemDefaultCharSize) : 8); // Second call gets the detailed data buffer //Debug.WriteLine("usbGenericHidCommunication:findHidDevices() -> Getting details of the device"); SetupApi.SetupDiGetDeviceInterfaceDetail (deviceInfoSet, ref deviceInterfaceData, detailDataBuffer, bufferSize, ref bufferSize, IntPtr.Zero); // Skip over cbsize (4 bytes) to get the address of the devicePathName. var pDevicePathName = new IntPtr(detailDataBuffer.ToInt32() + 4); // Get the String containing the devicePathName. DevicePathNames.Add(Marshal.PtrToStringAuto(pDevicePathName)); //Debug.WriteLine(string.Format("usbGenericHidCommunication:findHidDevices() -> Found matching device (memberIndex {0})", memberIndex)); deviceFound = true; } listIndex += 1; }while (lastDevice != true); } catch (Exception) { // Something went badly wrong... output some debug and return false to indicated device discovery failure Debug.WriteLine("findHidDevices() -> EXCEPTION: Something went south whilst trying to get devices with matching GUIDs - giving up!"); return(false); } finally { // Clean up the unmanaged memory allocations if (detailDataBuffer != IntPtr.Zero) { // Free the memory allocated previously by AllocHGlobal. Marshal.FreeHGlobal(detailDataBuffer); } if (deviceInfoSet != IntPtr.Zero) { SetupApi.SetupDiDestroyDeviceInfoList(deviceInfoSet); } } if (deviceFound) { Debug.WriteLine(string.Format("findHidDevices() -> Found {0} devices with matching GUID", (DevicePathNames.Count).ToString(CultureInfo.InvariantCulture))); } else { Debug.WriteLine("findHidDevices() -> No matching devices found"); } return(deviceFound); }
public static extern bool SetupDiGetDeviceInterfaceDetail(IntPtr hDevInfo, ref SpDeviceInterfaceData deviceInterfaceData, ref SpDeviceInterfaceDetailData deviceInterfaceDetailData, uint deviceInterfaceDetailDataSize, out uint requiredSize, ref SpDeviceInfoData deviceInfoData);