private static extern Boolean SetupDiEnumDeviceInterfaces( IntPtr hDevInfo, ref SP_DEVINFO_DATA devInfo, ref Guid interfaceClassGuid, UInt32 memberIndex, ref SP_DEVICE_INTERFACE_DATA deviceInterfaceData );
public static extern IntPtr SetupDiOpenDevRegKey( IntPtr hDeviceInfoSet, ref SP_DEVINFO_DATA deviceInfoData, int scope, int hwProfile, int parameterRegistryValueKind, int samDesired);
private static IEnumerable<SP_DEVICE_INTERFACE_DATA> SetupDiEnumDeviceInterfacesHelper( SafeDeviceInfoSetHandle lpDeviceInfoSet, SP_DEVINFO_DATA? deviceInfoData, Guid interfaceClassGuid) { int index = 0; while (true) { var data = SP_DEVICE_INTERFACE_DATA.Create(); bool result = SetupDiEnumDeviceInterfaces( lpDeviceInfoSet, deviceInfoData, ref interfaceClassGuid, index, ref data); if (!result) { var lastError = GetLastError(); if (lastError != Win32ErrorCode.ERROR_NO_MORE_ITEMS) { throw new Win32Exception(lastError); } yield break; } yield return data; index++; } }
static void Main(string[] args) { int deviceCount = 0; IntPtr deviceList = IntPtr.Zero; // GUID for processor classid Guid processorGuid = new Guid("{50127dc3-0f36-415e-a6cc-4cb3be910b65}"); try { // get a list of all processor devices deviceList = SetupDiGetClassDevs(ref processorGuid, "ACPI", IntPtr.Zero, (int)DIGCF.PRESENT); // attempt to process each item in the list for (int deviceNumber = 0; ; deviceNumber++) { SP_DEVINFO_DATA deviceInfo = new SP_DEVINFO_DATA(); deviceInfo.cbSize = Marshal.SizeOf(deviceInfo); // attempt to read the device info from the list, if this fails, we're at the end of the list if (!SetupDiEnumDeviceInfo(deviceList, deviceNumber, ref deviceInfo)) { deviceCount = deviceNumber - 1; break; } } } finally { if (deviceList != IntPtr.Zero) { SetupDiDestroyDeviceInfoList(deviceList); } } Console.WriteLine("Number of cores: {0}{1}{2}{3}", Environment.MachineName, Environment.ExitCode, Environment.CurrentDirectory,Environment.SystemDirectory); }
SetupDiGetDeviceRegistryPropertyA( IntPtr DeviceInfoSet, SP_DEVINFO_DATA DeviceInfoData, UInt32 Property, UInt32 PropertyRegDataType, StringBuilder PropertyBuffer, UInt32 PropertyBufferSize, IntPtr RequiredSize);
public DeviceInfo(DeviceEnumerator deviceEnumerator, SP_DEVINFO_DATA devinfoData, string devicePath, string deviceID, string userFriendlyName) { this.deviceEnumerator = deviceEnumerator; this.devinfoData = devinfoData; DevicePath = devicePath; DeviceID = deviceID; UserFriendlyName = userFriendlyName; }
static extern Boolean SetupDiGetDeviceInterfaceDetail( IntPtr hDevInfo, ref SP_DEVICE_INTERFACE_DATA deviceInterfaceData, ref SP_DEVICE_INTERFACE_DETAIL_DATA deviceInterfaceDetailData, UInt32 deviceInterfaceDetailDataSize, out UInt32 requiredSize, ref SP_DEVINFO_DATA deviceInfoData );
/// <summary> /// Retrieves a COM Port Name from the friendly name prefix /// </summary> /// <param name="friendlyNamePrefix">Prefix to search with</param> /// <returns></returns> public static string ComPortNameFromFriendlyNamePrefix(string friendlyNamePrefix) { const string className = "Ports"; Guid[] guids = GetClassGUIDs(className); System.Text.RegularExpressions.Regex friendlyNameToComPort = new System.Text.RegularExpressions.Regex(@".? \((COM\d+)\)$"); // "..... (COMxxx)" -> COMxxxx foreach (Guid guid in guids) { // We start at the "root" of the device tree and look for all // devices that match the interface GUID of a disk Guid guidClone = guid; IntPtr h = SetupDiGetClassDevs(ref guidClone, IntPtr.Zero, IntPtr.Zero, DIGCF_PRESENT | DIGCF_PROFILE); if (h.ToInt32() != INVALID_HANDLE_VALUE) { int nDevice = 0; while (true) { SP_DEVINFO_DATA da = new SP_DEVINFO_DATA(); da.cbSize = (uint)Marshal.SizeOf(da); if (0 == SetupDiEnumDeviceInfo(h, nDevice++, ref da)) break; uint RegType; byte[] ptrBuf = new byte[BUFFER_SIZE]; uint RequiredSize; if (SetupDiGetDeviceRegistryProperty(h, ref da, (uint)SPDRP.FRIENDLYNAME, out RegType, ptrBuf, BUFFER_SIZE, out RequiredSize)) { const int utf16terminatorSize_bytes = 2; string friendlyName = System.Text.UnicodeEncoding.Unicode.GetString(ptrBuf, 0, (int)RequiredSize - utf16terminatorSize_bytes); if (!friendlyName.StartsWith(friendlyNamePrefix)) continue; if (!friendlyNameToComPort.IsMatch(friendlyName)) continue; return friendlyNameToComPort.Match(friendlyName).Groups[1].Value; } } // devices SetupDiDestroyDeviceInfoList(h); } } // class guids return null; }
public static unsafe IEnumerable<SP_DEVICE_INTERFACE_DATA> SetupDiEnumDeviceInterfaces( SafeDeviceInfoSetHandle lpDeviceInfoSet, SP_DEVINFO_DATA* deviceInfoData, Guid interfaceClassGuid) { // Copy out the value of the struct pointed to (if any) so that // the caller does not need to remember to keep the pointer fixed // for the entire enumeration. var deviceInfoDataCopy = deviceInfoData != null ? (SP_DEVINFO_DATA?)*deviceInfoData : null; return SetupDiEnumDeviceInterfacesHelper( lpDeviceInfoSet, deviceInfoDataCopy, interfaceClassGuid); }
Boolean GetRegProp(IntPtr deviceInfoSet, ref SP_DEVINFO_DATA devInfo, uint property, out string propertyVal) { uint RequiredSize = 0; uint RegType; propertyVal = null; SetupDiGetDeviceRegistryProperty(deviceInfoSet, ref devInfo, property, out RegType, IntPtr.Zero, 0, out RequiredSize); if (RequiredSize > 0) { IntPtr ptrBuf = Marshal.AllocHGlobal((int)RequiredSize); if (SetupDiGetDeviceRegistryProperty(deviceInfoSet, ref devInfo, property, out RegType, ptrBuf, RequiredSize, out RequiredSize)) propertyVal = Marshal.PtrToStringAuto(ptrBuf); Marshal.FreeHGlobal(ptrBuf); } return propertyVal != null; }
Boolean GetInstanceId(IntPtr deviceInfoSet, ref SP_DEVINFO_DATA devInfo, out string instanceId) { uint RequiredSize = 256; instanceId = null; IntPtr ptrBuf = Marshal.AllocHGlobal((int)RequiredSize); if (SetupDiGetDeviceInstanceId(deviceInfoSet, ref devInfo, ptrBuf, RequiredSize, out RequiredSize)) instanceId = Marshal.PtrToStringAuto(ptrBuf); else if (RequiredSize > 0) { Marshal.ReAllocHGlobal(ptrBuf, new IntPtr(RequiredSize)); if (SetupDiGetDeviceInstanceId(deviceInfoSet, ref devInfo, ptrBuf, RequiredSize, out RequiredSize)) instanceId = Marshal.PtrToStringAuto(ptrBuf); } Marshal.FreeHGlobal(ptrBuf); return instanceId != null; }
public static unsafe string SetupDiGetDeviceInterfaceDetail( SafeDeviceInfoSetHandle deviceInfoSet, SP_DEVICE_INTERFACE_DATA interfaceData, SP_DEVINFO_DATA* deviceInfoData) { int requiredSize; // First call to get the size to allocate SetupDiGetDeviceInterfaceDetail( deviceInfoSet, ref interfaceData, null, 0, &requiredSize, deviceInfoData); // 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); } fixed (byte* pBuffer = new byte[requiredSize]) { var pDetail = (SP_DEVICE_INTERFACE_DETAIL_DATA*)pBuffer; pDetail->cbSize = SP_DEVICE_INTERFACE_DETAIL_DATA.ReportableStructSize; // Second call to get the value var success = SetupDiGetDeviceInterfaceDetail( deviceInfoSet, ref interfaceData, pDetail, requiredSize, null, null); if (!success) { Marshal.ThrowExceptionForHR(Marshal.GetHRForLastWin32Error()); return null; } return SP_DEVICE_INTERFACE_DETAIL_DATA.GetDevicePath(pDetail); } }
public static bool Create(string className, Guid classGuid, string node) { var deviceInfoSet = (IntPtr)(-1); var deviceInfoData = new SP_DEVINFO_DATA(); try { deviceInfoSet = SetupDiCreateDeviceInfoList(ref classGuid, IntPtr.Zero); if (deviceInfoSet == (IntPtr)(-1)) { return false; } deviceInfoData.cbSize = Marshal.SizeOf(deviceInfoData); if ( !SetupDiCreateDeviceInfo(deviceInfoSet, className, ref classGuid, null, IntPtr.Zero, DICD_GENERATE_ID, ref deviceInfoData)) { return false; } if ( !SetupDiSetDeviceRegistryProperty(deviceInfoSet, ref deviceInfoData, SPDRP_HARDWAREID, node, node.Length * 2)) { return false; } if (!SetupDiCallClassInstaller(DIF_REGISTERDEVICE, deviceInfoSet, ref deviceInfoData)) { return false; } } finally { if (deviceInfoSet != (IntPtr)(-1)) { SetupDiDestroyDeviceInfoList(deviceInfoSet); } } return true; }
public static Guid GuidDevinterfaceUSBDevice = new Guid(GUID_DEVINTERFACE_USB_DEVICE); // USB devices #endregion /// <summary> /// ISBデバイスのDescriptionの一覧を作成する /// </summary> public static IList<string> MakeDeviceList() { List<string> list = new List<string>(); Guid guid = Guid.Empty; IntPtr DevInfoHandle = IntPtr.Zero; //DevInfoHandle = SetupDiGetClassDevs( // IntPtr.Zero, null, IntPtr.Zero, // DIGCF_ALLCLASSES | DIGCF_PRESENT); // USBデバイスだけ列挙 DevInfoHandle = SetupDiGetClassDevs( ref GuidDevinterfaceUSBDevice, IntPtr.Zero, IntPtr.Zero, DIGCF_DEVICEINTERFACE | DIGCF_PRESENT); SP_DEVINFO_DATA DevInfoData = new SP_DEVINFO_DATA { classGuid = Guid.Empty, devInst = 0, reserved = IntPtr.Zero }; DevInfoData.cbSize = (uint)Marshal.SizeOf(DevInfoData);// 32, // 28 When 32-Bit, 32 When 64-Bit, for (uint i = 0; SetupDiEnumDeviceInfo(DevInfoHandle, i, ref DevInfoData); i++) { string str = GetStringPropertyForDevice( DevInfoHandle, DevInfoData, (uint)SetupDiGetDeviceRegistryPropertyEnum.SPDRP_DEVICEDESC); if (str != null) list.Add(str.Replace("\0", "")); else str = "(null)"; // I-O DATA GV-USB2t.gvusb2.name%;I-O DATA GV-USB2 Debug.WriteLine(str.Replace("\0", "")); } SetupDiDestroyDeviceInfoList(DevInfoHandle); return list; }
public string GetDevicePath(Guid classGuid) { IntPtr hDevInfo = IntPtr.Zero; try { hDevInfo = SetupDiGetClassDevs(ref classGuid, null, IntPtr.Zero, DiGetClassFlags.DIGCF_DEVICEINTERFACE | DiGetClassFlags.DIGCF_PRESENT); if (hDevInfo.ToInt64() <= 0) { throw new Win32Exception(Marshal.GetLastWin32Error()); } SP_DEVICE_INTERFACE_DATA dia = new SP_DEVICE_INTERFACE_DATA(); dia.cbSize = (uint)Marshal.SizeOf(dia); SP_DEVINFO_DATA devInfo = new SP_DEVINFO_DATA(); devInfo.cbSize = (UInt32)Marshal.SizeOf(devInfo); UInt32 i = 0; // start the enumeration if (!SetupDiEnumDeviceInterfaces(hDevInfo, null, ref classGuid, i, dia)) { throw new Win32Exception(Marshal.GetLastWin32Error()); } SP_DEVICE_INTERFACE_DETAIL_DATA didd = new SP_DEVICE_INTERFACE_DETAIL_DATA(); didd.cbSize = 4 + Marshal.SystemDefaultCharSize; // trust me :) UInt32 requiredSize = 0; if (!SetupDiGetDeviceInterfaceDetail(hDevInfo, dia, ref didd, 256, out requiredSize, devInfo)) { throw new Win32Exception(Marshal.GetLastWin32Error()); } return didd.DevicePath; } finally { SetupDiDestroyDeviceInfoList(hDevInfo); } }
private static byte[] GetProperty(IntPtr deviceInfoSet, SP_DEVINFO_DATA deviceInfoData, SPDRP property, out int regType) { uint requiredSize; if (!SetupDiGetDeviceRegistryProperty(deviceInfoSet, ref deviceInfoData, property, IntPtr.Zero, IntPtr.Zero, 0, out requiredSize)) { if (Marshal.GetLastWin32Error() != ERROR_INSUFFICIENT_BUFFER) throw APIException.Win32("Failed to get buffer size for device registry property."); } byte[] buffer = new byte[requiredSize]; if (!SetupDiGetDeviceRegistryProperty(deviceInfoSet, ref deviceInfoData, property, out regType, buffer, (uint)buffer.Length, out requiredSize)) throw APIException.Win32("Failed to get device registry property."); return buffer; }
protected static bool DevicePresent(Guid g) { // Used to capture how many bytes are returned by system calls UInt32 theBytesReturned = 0; // SetupAPI32.DLL Data Structures SP_DEVINFO_DATA theDevInfoData = new SP_DEVINFO_DATA(); theDevInfoData.cbSize = Marshal.SizeOf(theDevInfoData); IntPtr theDevInfo = SetupDiGetClassDevs(ref g, IntPtr.Zero, IntPtr.Zero, (int)(DiGetClassFlags.DIGCF_PRESENT | DiGetClassFlags.DIGCF_DEVICEINTERFACE)); SP_DEVICE_INTERFACE_DATA theInterfaceData = new SP_DEVICE_INTERFACE_DATA(); theInterfaceData.cbSize = Marshal.SizeOf(theInterfaceData); // Check for the device if (!SetupDiEnumDeviceInterfaces(theDevInfo, IntPtr.Zero, ref g, 0, ref theInterfaceData) && GetLastError() == ERROR_NO_MORE_ITEMS) return false; // Get the device's file path SetupDiGetDeviceInterfaceDetail(theDevInfo, ref theInterfaceData, IntPtr.Zero, 0, ref theBytesReturned, IntPtr.Zero); return !(theBytesReturned <= 0); }
/// <summary> /// Installs a driver using its INF file /// </summary> /// <param name="filePath">Relative or absolute INF file path</param> /// <param name="hardwareID">ComponentID</param> /// <returns></returns> public static bool InstallInfDriver(string filePath, string hardwareID, string description = "") { // TODO: Win10 got wrong bitness onetime (???) if (IntPtr.Size == 4 && Environment.Is64BitOperatingSystem) { MessageBox.Show("This process is 32-bit but the OS is 64-bit. Only 64-bit processes can install 64-bit direvers.", "Driver Setup", MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button2, MessageBoxOptions.ServiceNotification); return false; } filePath = Path.GetFullPath(filePath); GUID classGuid = new GUID(); char[] className = new char[MAX_CLASS_NAME_LEN]; uint requiredSize = 0; SP_DEVINFO_DATA deviceInfoData = new SP_DEVINFO_DATA(); deviceInfoData.cbSize = (uint)Marshal.SizeOf(deviceInfoData); // Use the INF File to extract the Class GUID if (!SetupDiGetINFClass(filePath, ref classGuid, className, MAX_CLASS_NAME_LEN, ref requiredSize)) return false; // Create the container for the to-be-created Device Information Element IntPtr deviceInfoSet = SetupDiCreateDeviceInfoList(ref classGuid, IntPtr.Zero); if (deviceInfoSet == Kernel32.INVALID_HANDLE_VALUE) return false; // Now create the element. Use the Class GUID and Name from the INF file if (!SetupDiCreateDeviceInfo(deviceInfoSet, new string(className), ref classGuid, description, IntPtr.Zero, DICD_GENERATE_ID, ref deviceInfoData)) return false; // Add the HardwareID to the Device's HardwareID property if (!SetupDiSetDeviceRegistryProperty(deviceInfoSet, ref deviceInfoData, SPDRP_HARDWAREID, Encoding.Unicode.GetBytes(hardwareID), (uint)Encoding.Unicode.GetByteCount(hardwareID))) return false; // Transform the registry element into an actual devnode in the PnP HW tree if (!SetupDiCallClassInstaller(DI_FUNCTION.DIF_REGISTERDEVICE, deviceInfoSet, ref deviceInfoData)) return false; SetupDiDestroyDeviceInfoList(deviceInfoSet); // Update the driver for the device we just created if (!Newdev.UpdateDriverForPlugAndPlayDevices(IntPtr.Zero, hardwareID, filePath, Newdev.INSTALLFLAG_FORCE, IntPtr.Zero)) return false; return true; }
public static DeviceInfo[] GetInterfaces() { var list = new List <DeviceInfo>(); Guid hidGuid = Guid.Empty; NativeMethods.HidD_GetHidGuid(ref hidGuid); int requiredSize3 = 0; var interfaceData = new SP_DEVICE_INTERFACE_DATA(); interfaceData.Initialize(); List <string> serials = new List <string>(); var deviceInfoSet = NativeMethods.SetupDiGetClassDevs(hidGuid, IntPtr.Zero, IntPtr.Zero, DIGCF.DIGCF_DEVICEINTERFACE); for (int i2 = 0; NativeMethods.SetupDiEnumDeviceInterfaces(deviceInfoSet, IntPtr.Zero, ref hidGuid, i2, ref interfaceData); i2++) { var deviceInfoData = new SP_DEVINFO_DATA(); deviceInfoData.Initialize(); bool success = NativeMethods.SetupDiGetDeviceInterfaceDetail(deviceInfoSet, ref interfaceData, IntPtr.Zero, 0, ref requiredSize3, IntPtr.Zero); IntPtr ptrDetails = Marshal.AllocHGlobal(requiredSize3); Marshal.WriteInt32(ptrDetails, (IntPtr.Size == 4) ? (4 + Marshal.SystemDefaultCharSize) : 8); success = NativeMethods.SetupDiGetDeviceInterfaceDetail(deviceInfoSet, ref interfaceData, ptrDetails, requiredSize3, ref requiredSize3, ref deviceInfoData); var interfaceDetail = (SP_DEVICE_INTERFACE_DETAIL_DATA)Marshal.PtrToStructure(ptrDetails, typeof(SP_DEVICE_INTERFACE_DETAIL_DATA)); var di = GetDeviceInfo(deviceInfoSet, deviceInfoData); di.DevicePath = interfaceDetail.DevicePath; var deviceHandle = deviceInfoData.DevInst; Marshal.FreeHGlobal(ptrDetails); // Open the device as a file so that we can query it with HID and read/write to it. var devHandle = NativeMethods.CreateFile( interfaceDetail.DevicePath, 0, FileShare.ReadWrite, IntPtr.Zero, FileMode.Open, 0, //WinNT.Overlapped IntPtr.Zero ); if (devHandle.IsInvalid) { continue; } var ha = new HIDD_ATTRIBUTES(); ha.Size = Marshal.SizeOf(ha); var success2 = NativeMethods.HidD_GetAttributes(devHandle, ref ha); string serial = ""; string phdesc = ""; if (success2) { IntPtr preparsedDataPtr = new IntPtr(); HIDP_CAPS caps = new HIDP_CAPS(); // Read out the 'pre-parsed data'. NativeMethods.HidD_GetPreparsedData(devHandle, ref preparsedDataPtr); // feed that to GetCaps. NativeMethods.HidP_GetCaps(preparsedDataPtr, ref caps); // Free the 'pre-parsed data'. NativeMethods.HidD_FreePreparsedData(ref preparsedDataPtr); // This could fail if the device was recently attached. // Maximum string length is 126 wide characters (2 bytes each) (not including the terminating NULL character). ulong capacity = (uint)(126 * Marshal.SystemDefaultCharSize + 2); var sb = new StringBuilder((int)capacity, (int)capacity); // Override manufacturer if found. if (NativeMethods.HidD_GetManufacturerString(devHandle, sb, sb.Capacity) && sb.Length > 0) { di.Manufacturer = sb.ToString(); } // Override ProductName if Found. if (NativeMethods.HidD_GetProductString(devHandle, sb, sb.Capacity) && sb.Length > 0) { di.Description = sb.ToString(); } serial = NativeMethods.HidD_GetSerialNumberString(devHandle, sb, sb.Capacity) ? sb.ToString() : ""; phdesc = NativeMethods.HidD_GetPhysicalDescriptor(devHandle, sb, sb.Capacity) ? sb.ToString() : ""; } uint parentDeviceInstance = 0; string parentDeviceId = null; var CRResult = NativeMethods.CM_Get_Parent(out parentDeviceInstance, deviceHandle, 0); if (CRResult == CR.CR_SUCCESS) { parentDeviceId = GetDeviceId(parentDeviceInstance); } list.Add(di); serials.Add(phdesc); devHandle.Close(); } NativeMethods.SetupDiDestroyDeviceInfoList(deviceInfoSet); deviceInfoSet = IntPtr.Zero; return(list.ToArray()); }
private static extern bool SetupDiGetDeviceInterfaceDetail(IntPtr deviceInfoSet, ref SP_DEVICE_INTERFACE_DATA deviceInterfaceData, IntPtr deviceInterfaceDetailData, int deviceInterfaceDetailDataSize, ref int requiredSize, SP_DEVINFO_DATA deviceInfoData);
private static extern bool DiInstallDevice( IntPtr hParent, IntPtr lpInfoSet, ref SP_DEVINFO_DATA DeviceInfoData, ref SP_DRVINFO_DATA DriverInfoData, DiFlags Flags, ref bool NeedReboot);
public static extern bool SetupDiGetDeviceRegistryProperty(IntPtr deviceInfoSet, ref SP_DEVINFO_DATA deviceInfoData, int propertyVal, int propertyRegDataType, byte[] propertyBuffer, int propertyBufferSize, IntPtr requiredSize);
public static extern bool SetupDiGetDeviceRegistryProperty(IntPtr lpInfoSet, SP_DEVINFO_DATA DeviceInfoData, UInt32 Property, UInt32 PropertyRegDataType, StringBuilder PropertyBuffer, UInt32 PropertyBufferSize, IntPtr RequiredSize);
public static extern bool SetupDiChangeState(IntPtr deviceInfoSet, [In] ref SP_DEVINFO_DATA deviceInfoData);
public static void DisableDevice(Func <string, bool> filter, bool disable = true) { IntPtr info = IntPtr.Zero; Guid NullGuid = Guid.Empty; try { info = SetupDiGetClassDevsW( ref NullGuid, null, IntPtr.Zero, DIGCF_ALLCLASSES); CheckError("SetupDiGetClassDevs"); SP_DEVINFO_DATA devdata = new SP_DEVINFO_DATA(); devdata.cbSize = (UInt32)Marshal.SizeOf(devdata); // Get first device matching device criterion. for (uint i = 0; ; i++) { SetupDiEnumDeviceInfo(info, i, out devdata); // if no items match filter, throw if (Marshal.GetLastWin32Error() == ERROR_NO_MORE_ITEMS) { CheckError("No device found matching filter.", 0xcffff); } CheckError("SetupDiEnumDeviceInfo"); string devicepath = GetStringPropertyForDevice(info, devdata, 1); // SPDRP_HARDWAREID // Uncomment to print name/path //Console.WriteLine(GetStringPropertyForDevice(info, // devdata, DEVPKEY_Device_DeviceDesc)); //Console.WriteLine(" {0}", devicepath); if (devicepath != null && filter(devicepath)) { break; } } SP_CLASSINSTALL_HEADER header = new SP_CLASSINSTALL_HEADER(); header.cbSize = (UInt32)Marshal.SizeOf(header); header.InstallFunction = DIF_PROPERTYCHANGE; SP_PROPCHANGE_PARAMS propchangeparams = new SP_PROPCHANGE_PARAMS(); propchangeparams.ClassInstallHeader = header; propchangeparams.StateChange = disable ? DICS_DISABLE : DICS_ENABLE; propchangeparams.Scope = DICS_FLAG_GLOBAL; propchangeparams.HwProfile = 0; SetupDiSetClassInstallParams(info, ref devdata, ref propchangeparams, (UInt32)Marshal.SizeOf(propchangeparams)); CheckError("SetupDiSetClassInstallParams"); SetupDiChangeState( info, ref devdata); CheckError("SetupDiChangeState"); } finally { if (info != IntPtr.Zero) { SetupDiDestroyDeviceInfoList(info); } } }
public static extern bool SetupDiGetDeviceProperty(IntPtr deviceInfo, ref SP_DEVINFO_DATA deviceInfoData, ref DEVPROPKEY propkey, ref ulong propertyDataType, byte[] propertyBuffer, int propertyBufferSize, ref int requiredSize, uint flags);
protected static extern Boolean SetupDiCreateDeviceInfo(IntPtr DeviceInfoSet, String DeviceName, ref Guid ClassGuid, String DeviceDescription, IntPtr hwndParent, Int32 CreationFlags, ref SP_DEVINFO_DATA DeviceInfoData);
public static Boolean Find(Guid Target, ref String Path, ref String InstanceId, Int32 Instance = 0) { IntPtr detailDataBuffer = IntPtr.Zero; IntPtr deviceInfoSet = IntPtr.Zero; try { SP_DEVINFO_DATA deviceInterfaceData = new SP_DEVINFO_DATA(), da = new SP_DEVINFO_DATA(); Int32 bufferSize = 0, memberIndex = 0; deviceInfoSet = SetupDiGetClassDevs(ref Target, IntPtr.Zero, IntPtr.Zero, DIGCF_PRESENT | DIGCF_DEVICEINTERFACE); deviceInterfaceData.cbSize = da.cbSize = Marshal.SizeOf(deviceInterfaceData); while (SetupDiEnumDeviceInterfaces(deviceInfoSet, IntPtr.Zero, ref Target, memberIndex, ref deviceInterfaceData)) { SetupDiGetDeviceInterfaceDetail(deviceInfoSet, ref deviceInterfaceData, IntPtr.Zero, 0, ref bufferSize, ref da); { detailDataBuffer = Marshal.AllocHGlobal(bufferSize); Marshal.WriteInt32(detailDataBuffer, (IntPtr.Size == 4) ? (4 + Marshal.SystemDefaultCharSize) : 8); if (SetupDiGetDeviceInterfaceDetail(deviceInfoSet, ref deviceInterfaceData, detailDataBuffer, bufferSize, ref bufferSize, ref da)) { IntPtr pDevicePathName = detailDataBuffer + 4; Path = Marshal.PtrToStringAuto(pDevicePathName).ToUpper(); if (memberIndex == Instance) { Int32 nBytes = 256; IntPtr ptrInstanceBuf = Marshal.AllocHGlobal(nBytes); CM_Get_Device_ID(da.Flags, ptrInstanceBuf, nBytes, 0); InstanceId = Marshal.PtrToStringAuto(ptrInstanceBuf).ToUpper(); Marshal.FreeHGlobal(ptrInstanceBuf); return(true); } } else { Marshal.FreeHGlobal(detailDataBuffer); } } memberIndex++; } } catch (Exception ex) { Console.WriteLine("{0} {1}", ex.HelpLink, ex.Message); throw; } finally { if (deviceInfoSet != IntPtr.Zero) { SetupDiDestroyDeviceInfoList(deviceInfoSet); } } return(false); }
private static long GetDrivesDevInstByDeviceNumber(long DeviceNumber, DriveType DriveType) { Guid Type_Guid; switch (DriveType) { case DriveType.DRIVE_REMOVABLE: Type_Guid = new Guid(GUID_DEVINTERFACE_DISK); break; case DriveType.DRIVE_FIXED: Type_Guid = new Guid(GUID_DEVINTERFACE_DISK); break; case DriveType.DRIVE_CDROM: Type_Guid = new Guid(GUID_DEVINTERFACE_CDROM); break; default: return(0); } IntPtr hDevInfo = SetupDiGetClassDevs(ref Type_Guid, 0, IntPtr.Zero, DIGCF_PRESENT | DIGCF_DEVICEINTERFACE); if (hDevInfo.ToInt32() == INVALID_HANDLE_VALUE) { throw new Win32Exception(Marshal.GetLastWin32Error()); } try { for (int i = 0; ; i++) { SP_DEVICE_INTERFACE_DATA Interface_Data = new SP_DEVICE_INTERFACE_DATA(); if (!SetupDiEnumDeviceInterfaces(hDevInfo, null, ref Type_Guid, i, Interface_Data)) { int Error = Marshal.GetLastWin32Error(); if (Error != ERROR_NO_MORE_ITEMS) { throw new Win32Exception(Error); } break; } SP_DEVINFO_DATA devData = new SP_DEVINFO_DATA(); int Size = 0; if (!SetupDiGetDeviceInterfaceDetail(hDevInfo, Interface_Data, IntPtr.Zero, 0, ref Size, devData)) { int Error = Marshal.GetLastWin32Error(); if (Error != ERROR_INSUFFICIENT_BUFFER) { throw new Win32Exception(Error); } } IntPtr Buffer = Marshal.AllocHGlobal(Size); try { SP_DEVICE_INTERFACE_DETAIL_DATA Interface_Detail_Data = new SP_DEVICE_INTERFACE_DETAIL_DATA { cbSize = Marshal.SizeOf(typeof(SP_DEVICE_INTERFACE_DETAIL_DATA)) }; Marshal.StructureToPtr(Interface_Detail_Data, Buffer, false); if (!SetupDiGetDeviceInterfaceDetail(hDevInfo, Interface_Data, Buffer, Size, ref Size, devData)) { throw new Win32Exception(Marshal.GetLastWin32Error()); } string DevicePath = Marshal.PtrToStringAuto((IntPtr)((int)Buffer + Marshal.SizeOf(typeof(int)))); IntPtr hDrive = CreateFile(DevicePath, 0, FILE_SHARE_READ | FILE_SHARE_WRITE, IntPtr.Zero, OPEN_EXISTING, 0, IntPtr.Zero); if (hDrive.ToInt32() != INVALID_HANDLE_VALUE && DeviceNumber == GetDeviceNumber(hDrive)) { return(devData.devInst); } } finally { Marshal.FreeHGlobal(Buffer); } } } finally { SetupDiDestroyDeviceInfoList(hDevInfo); } return(0); }
private static extern bool SetupDiEnumDeviceInterfaces( IntPtr deviceInfoSet, SP_DEVINFO_DATA deviceInfoData, ref Guid interfaceClassGuid, int memberIndex, SP_DEVICE_INTERFACE_DATA deviceInterfaceData);
private static DeviceDetails GetDeviceDetails(string devicePath, IntPtr deviceInfoSet, SP_DEVINFO_DATA deviceInfoData) { DeviceDetails details = new(); details.DevicePath = devicePath; details.DeviceDescription = GetStringProperty(deviceInfoSet, deviceInfoData, SPDRP.SPDRP_DEVICEDESC); details.Manufacturer = GetStringProperty(deviceInfoSet, deviceInfoData, SPDRP.SPDRP_MFG); // Heathcliff74 details.BusName = ""; try { details.BusName = GetStringProperty(deviceInfoSet, deviceInfoData, new DEVPROPKEY(new Guid(0x540b947e, 0x8b40, 0x45bc, 0xa8, 0xa2, 0x6a, 0x0b, 0x89, 0x4c, 0xbd, 0xa2), 4)); } catch { } string[] hardwareIDs = GetMultiStringProperty(deviceInfoSet, deviceInfoData, SPDRP.SPDRP_HARDWAREID); Regex regex = new("^USB\\\\VID_([0-9A-F]{4})&PID_([0-9A-F]{4})", RegexOptions.IgnoreCase); foreach (string hardwareID in hardwareIDs) { Match match = regex.Match(hardwareID); if (match.Success) { details.VID = ushort.Parse(match.Groups[1].Value, System.Globalization.NumberStyles.AllowHexSpecifier); details.PID = ushort.Parse(match.Groups[2].Value, System.Globalization.NumberStyles.AllowHexSpecifier); break; } } // Heathcliff74 // Not all devices have numeric VID and PID // // if (!foundVidPid) // throw new APIException("Failed to find VID and PID for USB device. No hardware ID could be parsed."); return(details); }
static internal extern bool SetupDiEnumDeviceInfo(IntPtr deviceInfoSet, int memberIndex, ref SP_DEVINFO_DATA deviceInfoData);
static extern bool SetupDiEnumDeviceInfo(IntPtr DeviceInfoSet, uint MemberIndex, ref SP_DEVINFO_DATA DeviceInfoData);
/// <summary> /// C Code by http://www.reddit.com/user/chrisgzy /// Converted to C# by http://www.reddit.com/user/billism /// </summary> private IntPtr GetDeviceHandle(uint uiVID, uint uiPID, uint uiMI) { IntPtr deviceInfo = SetupDiGetClassDevs(ref GUID_DEVINTERFACE_HID, IntPtr.Zero, IntPtr.Zero, DIGCF_PRESENT | DIGCF_DEVICEINTERFACE); if (deviceInfo.ToInt64() == INVALID_HANDLE_VALUE) { return(IntPtr.Zero); } IntPtr returnPointer = IntPtr.Zero; SP_DEVINFO_DATA deviceData = new SP_DEVINFO_DATA(); deviceData.cbSize = (uint)Marshal.SizeOf(deviceData); for (uint i = 0; SetupDiEnumDeviceInfo(deviceInfo, i, ref deviceData); ++i) { IntPtr deviceId = Marshal.AllocHGlobal(MAX_DEVICE_ID_LEN); // was wchar_t[] type // CM_Get_Device_ID was CM_Get_Device_IDW in C++ code if (CM_Get_Device_ID(deviceData.devInst, deviceId, MAX_DEVICE_ID_LEN, 0) != 0) { continue; } if (!IsMatchingDevice(deviceId, uiVID, uiPID, uiMI)) { continue; } SP_DEVICE_INTERFACE_DATA interfaceData = new SP_DEVICE_INTERFACE_DATA(); // C code used SP_INTERFACE_DEVICE_DATA interfaceData.cbSize = (uint)Marshal.SizeOf(interfaceData); if (!SetupDiEnumDeviceInterfaces(deviceInfo, ref deviceData, ref GUID_DEVINTERFACE_HID, 0, ref interfaceData)) { break; } uint requiredSize = 0; SetupDiGetDeviceInterfaceDetail(deviceInfo, ref interfaceData, IntPtr.Zero, 0, out requiredSize, IntPtr.Zero); // var lastError = Marshal.GetLastWin32Error(); SP_DEVICE_INTERFACE_DETAIL_DATA interfaceDetailData = new SP_DEVICE_INTERFACE_DETAIL_DATA(); if (IntPtr.Size == 8) // for 64 bit operating systems { interfaceDetailData.cbSize = 8; } else { interfaceDetailData.cbSize = 4 + (uint)Marshal.SystemDefaultCharSize; // for 32 bit systems } if (!SetupDiGetDeviceInterfaceDetail(deviceInfo, ref interfaceData, ref interfaceDetailData, requiredSize, IntPtr.Zero, IntPtr.Zero)) { break; } //var deviceHandle = CreateFile(interfaceDetailData.DevicePath, GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, IntPtr.Zero, OPEN_EXISTING, FILE_FLAG_OVERLAPPED, IntPtr.Zero); var deviceHandle = CreateFile(interfaceDetailData.DevicePath, GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, IntPtr.Zero, OPEN_EXISTING, 0, IntPtr.Zero); if (deviceHandle.ToInt64() == INVALID_HANDLE_VALUE) { break; } returnPointer = deviceHandle; byte usb_pkt = new byte(); usb_pkt = 0; bool res = HidD_SetFeature(returnPointer, ref usb_pkt, 65); break; } SetupDiDestroyDeviceInfoList(deviceInfo); return(returnPointer); }
private static extern Boolean SetupDiEnumDeviceInfo(IntPtr DeviceInfoSet, UInt32 MemberIndex, ref SP_DEVINFO_DATA DeviceInfoData);
public List <DeviceEntity> GetHiddenDevice() { WSDLogger.WriterDebugger("Start GetHiddenDevice"); SP_DEVINFO_DATA DeviceInfoData = new SP_DEVINFO_DATA(); List <DeviceEntity> list = new List <DeviceEntity>(); List <DeviceEntity> listCurrent = new List <DeviceEntity>(); IntPtr hDevInfo = SetupDiGetClassDevs(GUID_DEVCLASS_PORTS, 0, IntPtr.Zero, DIGCF_NOSET); if (hDevInfo.ToInt64() == -1) { WSDLogger.WriterDebugger("SetupDiGetClassDevs: 获取设备错误。"); } else { DeviceInfoData.cbSize = Marshal.SizeOf(DeviceInfoData); DeviceInfoData.devInst = 0; DeviceInfoData.classGuid = System.Guid.Empty; DeviceInfoData.reserved = 0; var devs = SetupDiGetClassDevsExW(GUID_DEVCLASS_PORTS, null, IntPtr.Zero, DIGCF_NOSET, null, null, 0); var devsNow = SetupDiGetClassDevsExW(GUID_DEVCLASS_PORTS, null, IntPtr.Zero, DIGCF_PRESENT, null, null, 0); if (devsNow.ToInt64() != -1) { for (uint i = 0; SetupDiEnumDeviceInfo(devsNow, i, DeviceInfoData); i++) { DeviceEntity entity = new DeviceEntity(); StringBuilder DeviceName = new StringBuilder("", 254); bool resName = SetupDiGetDeviceRegistryPropertyA(devs, DeviceInfoData, SPDRP_FRIENDLYNAME, 0, DeviceName, MAX_DEV_LEN, IntPtr.Zero); if (!resName) { } else { entity.DeviceName = DeviceName.ToString(); } StringBuilder DeviceID = new StringBuilder("", 254); if (CM_Get_Device_IDA(DeviceInfoData.devInst, DeviceID, 254, 0) == CR_SUCCESS) { entity.DeviceID = DeviceID.ToString(); } listCurrent.Add(entity); } } for (uint i = 0; SetupDiEnumDeviceInfo(devs, i, DeviceInfoData); i++) { DeviceEntity entity = new DeviceEntity(); StringBuilder DeviceID = new StringBuilder("", 254); if (CM_Get_Device_IDA(DeviceInfoData.devInst, DeviceID, 254, 0) == CR_SUCCESS) { entity.DeviceID = DeviceID.ToString(); } if (listCurrent.Exists(p => p.DeviceID == DeviceID.ToString())) { continue; } else { StringBuilder DeviceName = new StringBuilder("", 254); bool resName = SetupDiGetDeviceRegistryPropertyA(devs, DeviceInfoData, SPDRP_FRIENDLYNAME, 0, DeviceName, MAX_DEV_LEN, IntPtr.Zero); if (!resName) { } else { entity.DeviceName = DeviceName.ToString(); } StringBuilder Mfg = new StringBuilder("", 254); bool resHardwareMfg = SetupDiGetDeviceRegistryPropertyA(devs, DeviceInfoData, SPDRP_MFG, 0, Mfg, MAX_DEV_LEN, IntPtr.Zero); if (!resHardwareMfg) { } else { entity.DevicePIDVID = Mfg.ToString(); } StringBuilder realPath = new StringBuilder("", 2047); bool resHardwareRealPath = SetupDiGetDeviceRegistryPropertyA(devs, DeviceInfoData, SPDRP_LOCATION_PATHS, 0, realPath, MAX_DEV_LEN, IntPtr.Zero); if (!resHardwareRealPath) { } else { entity.RealTimePath = realPath.ToString(); } StringBuilder installState = new StringBuilder("", 64); bool resHardwareInstallState = SetupDiGetDeviceRegistryPropertyA(devs, DeviceInfoData, SPDRP_INSTALL_STATE, 0, installState, MAX_DEV_LEN, IntPtr.Zero); if (!resHardwareInstallState) { } else { entity.InstallState = installState.ToString(); } //bool isHidde = !SetupDiSelectDevice(devsNow, DeviceInfoData); entity.IsHiddenDevice = true; list.Add(entity); } } SetupDiDestroyDeviceInfoList(devs); SetupDiDestroyDeviceInfoList(devsNow); ScanForHardwareChange(); } WSDLogger.WriterDebugger("End GetHiddenDevice"); return(list); }
private static extern bool SetupDiEnumDeviceInterfaces(IntPtr DeviceInfoSet, IntPtr DeviceInfoData, ref Guid InterfaceClassGuid, int MemberIndex, ref SP_DEVINFO_DATA DeviceInterfaceData);
private Device(IntPtr hDevInfo, SP_DEVINFO_DATA data) { _hDevInfo = hDevInfo; _data = data; }
private static extern bool SetupDiOpenDeviceInfo(IntPtr DeviceInfoSet, string DeviceInstanceId, IntPtr hwndParent, int Flags, ref SP_DEVINFO_DATA DeviceInfoData);
protected static extern Boolean SetupDiEnumDeviceInterfaces(IntPtr DeviceInfoSet, IntPtr DeviceInfoData, ref Guid InterfaceClassGuid, Int32 MemberIndex, ref SP_DEVINFO_DATA DeviceInterfaceData);
private static extern bool SetupDiGetDeviceProperty(IntPtr DeviceInfoSet, ref SP_DEVINFO_DATA DeviceInfoData, ref DEVPROPKEY propertyKey, out int propertyType, IntPtr propertyBuffer, int propertyBufferSize, out int requiredSize, int flags);
public static extern bool SetupDiEnumDeviceInfo(IntPtr lpInfoSet, UInt32 dwIndex, SP_DEVINFO_DATA devInfoData);
protected static extern Boolean SetupDiGetDeviceInterfaceDetail(IntPtr DeviceInfoSet, ref SP_DEVINFO_DATA DeviceInterfaceData, IntPtr DeviceInterfaceDetailData, Int32 DeviceInterfaceDetailDataSize, ref Int32 RequiredSize, ref SP_DEVINFO_DATA DeviceInfoData);
private static extern bool SetupDiGetDeviceInterfaceDetail(IntPtr DeviceInfoSet, ref SP_DEVINFO_DATA DeviceInterfaceData, IntPtr DeviceInterfaceDetailData, int DeviceInterfaceDetailDataSize, ref int RequiredSize, ref SP_DEVINFO_DATA DeviceInfoData);
protected static extern Boolean SetupDiOpenDeviceInfo(IntPtr DeviceInfoSet, String DeviceInstanceId, IntPtr hwndParent, Int32 Flags, ref SP_DEVINFO_DATA DeviceInfoData);
public static extern bool SetupDiGetDevicePropertyKeys(IntPtr deviceInfo, ref SP_DEVINFO_DATA deviceInfoData, [Out, Optional, MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 3)] DEVPROPKEY[] PropertyKeyArray, uint PropertyKeyCount, out uint RequiredPropertyKeyCount, uint Flags = 0);
static internal extern bool SetupDiCallClassInstaller(int installFunction, IntPtr deviceInfoSet, ref SP_DEVINFO_DATA deviceInfoData);
public static string GetDeviceManufacturer(IntPtr deviceInfoSet, SP_DEVINFO_DATA deviceInfoData) { var deviceManufacturer = GetStringPropertyForDevice(deviceInfoSet, deviceInfoData, SPDRP.SPDRP_MFG); return((deviceManufacturer ?? "").Trim()); }
static internal extern bool SetupDiGetDeviceInstanceId(IntPtr deviceInfoSet, ref SP_DEVINFO_DATA deviceInfoData, char[] deviceInstanceId, Int32 deviceInstanceIdSize, ref int requiredSize);
protected static extern Boolean SetupDiSetDeviceRegistryProperty(IntPtr DeviceInfoSet, ref SP_DEVINFO_DATA DeviceInfoData, Int32 Property, [MarshalAs(UnmanagedType.LPWStr)] String PropertyBuffer, Int32 PropertyBufferSize);
static internal extern bool SetupDiSetClassInstallParams(IntPtr deviceInfoSet, ref SP_DEVINFO_DATA deviceInfoData, ref SP_PROPCHANGE_PARAMS classInstallParams, int classInstallParamsSize);
private static extern Boolean SetupDiGetDeviceInstanceId( IntPtr DeviceInfoSet, ref SP_DEVINFO_DATA DeviceInfoData, StringBuilder DeviceInstanceId, Int32 DeviceInstanceIdSize, IntPtr RequiredSize );
protected static extern Boolean SetupDiCallClassInstaller(Int32 InstallFunction, IntPtr DeviceInfoSet, ref SP_DEVINFO_DATA DeviceInfoData);
internal static extern bool SetupDiOpenDeviceInfo( IntPtr deviceInfoSet, string deviceInstanceId, IntPtr hwndParent, int openFlags, SP_DEVINFO_DATA deviceInfoData );
protected static extern Boolean SetupDiSetClassInstallParams(IntPtr DeviceInfoSet, ref SP_DEVINFO_DATA DeviceInterfaceData, ref SP_REMOVEDEVICE_PARAMS ClassInstallParams, Int32 ClassInstallParamsSize);
internal static extern bool SetupDiGetDeviceInterfaceDetail( IntPtr deviceInfoSet, SP_DEVICE_INTERFACE_DATA deviceInterfaceData, IntPtr deviceInterfaceDetailData, int deviceInterfaceDetailDataSize, ref int requiredSize, SP_DEVINFO_DATA deviceInfoData );
internal static extern bool SetupDiEnumDeviceInterfaces( IntPtr deviceInfoSet, SP_DEVINFO_DATA deviceInfoData, ref Guid interfaceClassGuid, int memberIndex, SP_DEVICE_INTERFACE_DATA deviceInterfaceData );
public static extern bool SetupDiEnumDeviceInfo(IntPtr DeviceInfoSet, uint MemberIndex, ref SP_DEVINFO_DATA DeviceInfoData);
public static bool childrenInstalled(string enumname) { UInt32 devStatus; UInt32 devProblemCode; IntPtr devlist = SetupDiGetClassDevs(IntPtr.Zero, enumname, IntPtr.Zero, DiGetClassFlags.DIGCF_PRESENT | DiGetClassFlags.DIGCF_ALLCLASSES); uint i = 0; SP_DEVINFO_DATA DevData = new SP_DEVINFO_DATA(); DevData.cbSize = (uint)Marshal.SizeOf(DevData); while(SetupDiEnumDeviceInfo(devlist, i , ref DevData)) { CM_Get_DevNode_Status(out devStatus, out devProblemCode, DevData.DevInst, 0); if ((devStatus & (uint)DNFlags.DN_STARTED) == 0) { Trace.WriteLine(enumname + " child not started "+devStatus.ToString() ); return false; } i++; } return true; }
private static extern bool SetupDiSetClassInstallParams(IntPtr DeviceInfoSet, ref SP_DEVINFO_DATA DeviceInterfaceData, ref SP_REMOVEDEVICE_PARAMS ClassInstallParams, int ClassInstallParamsSize);