C# 获取本机“设备管理器”信息列表

今天分享一个获取本机“设备管理器”的代码,希望可以帮到一些人吧!

class Externs
{
public const int DIGCF_ALLCLASSES = (0x00000004);
public const int DIGCF_PRESENT = (0x00000002);
public const int SPDRP_DEVICEDESC = (0x00000000);
public const int INVALID_HANDLE_VALUE = -1;
public const int MAX_DEV_LEN = 1000;
public static string[] portArray;


[DllImport("setupapi.dll", SetLastError = true)]
public static extern IntPtr SetupDiGetClassDevs(ref Guid gClass, UInt32 iEnumerator, IntPtr hParent, UInt32 nFlags);


[DllImport("setupapi.dll", SetLastError = true)]
public static extern int SetupDiDestroyDeviceInfoList(IntPtr lpInfoSet);


[DllImport("setupapi.dll", SetLastError = true)]
public static extern bool SetupDiEnumDeviceInfo(IntPtr lpInfoSet, UInt32 dwIndex, SP_DEVINFO_DATA devInfoData);


[DllImport("setupapi.dll", SetLastError = true)]
public static extern bool SetupDiGetDeviceRegistryProperty(IntPtr lpInfoSet, SP_DEVINFO_DATA DeviceInfoData, UInt32 Property, UInt32 PropertyRegDataType, 


StringBuilder PropertyBuffer, UInt32 PropertyBufferSize, IntPtr RequiredSize);




[StructLayout(LayoutKind.Sequential)]
public class SP_DEVINFO_DATA
{
public int cbSize;
public Guid classGuid;
public int devInst;
public ulong reserved;
};


public static string[] DiviceName()
{
List HWList = new List();
try
{
Guid myGUID = System.Guid.Empty;
IntPtr hDevInfo = Externs.SetupDiGetClassDevs(ref myGUID, 0, IntPtr.Zero, Externs.DIGCF_ALLCLASSES | Externs.DIGCF_PRESENT);


if (hDevInfo.ToInt32() == Externs.INVALID_HANDLE_VALUE)
{

throw new Exception("Invalid Handle");

}
Externs.SP_DEVINFO_DATA DeviceInfoData;
DeviceInfoData = new Externs.SP_DEVINFO_DATA();
DeviceInfoData.cbSize = 28;
DeviceInfoData.devInst = 0;
DeviceInfoData.classGuid = System.Guid.Empty;
DeviceInfoData.reserved = 0;
UInt32 i;
StringBuilder DeviceName = new StringBuilder("");
DeviceName.Capacity = Externs.MAX_DEV_LEN;
for (i = 0; Externs.SetupDiEnumDeviceInfo(hDevInfo, i, DeviceInfoData); i++)
{
while (!Externs.SetupDiGetDeviceRegistryProperty (hDevInfo, DeviceInfoData, Externs.SPDRP_DEVICEDESC, 0, DeviceName, Externs.MAX_DEV_LEN,IntPtr.Zero))
{
//Skip
}
HWList.Add(DeviceName.ToString());
}
Externs.SetupDiDestroyDeviceInfoList(hDevInfo);
}
catch (Exception ex)
{
throw new Exception("枚举设备列表出错", ex);
}
return HWList.ToArray();
}


通过调用Externs.DiviceName()就可以得到本机“设备管理器”的信息列表,例如USB、通讯端口、CPU等等信息。

你可能感兴趣的:(winform窗体)