C# 根据设备实例路径,获取父节点(父系)的设备实例路径
我们知道有时候系统的某些设备异常,可以通过(禁用启用)重启该设备。但是某些设备操作当前设备是没起作用的,例如扬声器设备,禁用后扬声器仍然可以播放声音,但是如果禁用了该设备的父节点则不再可以播放声音。
可以从设备管理器中查看
这里就是父节点
如果通过C#怎么获取该设备的父系实例路径呢?可以使用以下方式
/// <summary>定位到设备节点</summary> /// <param name="pdnDevInst"></param> /// <param name="pDeviceID"></param> /// <param name="ulFlags"></param> /// <returns></returns> [DllImport("setupapi.dll", SetLastError = true)] public static extern int CM_Locate_DevNodeA(ref int pdnDevInst, string pDeviceID, int ulFlags); /// <summary>获取节点父系</summary> /// <param name="pdnDevInst"></param> /// <param name="dnDevInst"></param> /// <param name="ulFlags"></param> /// <returns></returns> [DllImport("setupapi.dll")] public static extern int CM_Get_Parent(out uint pdnDevInst, uint dnDevInst, int ulFlags); /// <summary>获取节点id 长度</summary> /// <param name="pulLen"></param> /// <param name="dnDevInst"></param> /// <param name="flags"></param> /// <returns></returns> [DllImport("setupapi.dll", SetLastError = true)] public static extern int CM_Get_Device_ID_Size(out int pulLen, uint dnDevInst, int flags = 0); /// <summary>获取节点名称</summary> /// <param name="dnDevInst"></param> /// <param name="buffer"></param> /// <param name="bufferLen"></param> /// <param name="flags"></param> /// <returns></returns> [DllImport("setupapi.dll", CharSet = CharSet.Unicode)] public static extern int CM_Get_Device_ID( uint dnDevInst, char[] buffer, int bufferLen, int flags); /// <summary>获取设备父系</summary> /// <param name="deviceId">设备id</param> /// <param name="parentDeviceId">父系id</param> /// <returns></returns> public static bool TryGetDriverIdParent(string deviceId, out string parentDeviceId) { parentDeviceId = ""; try { int num1 = 0; int num2 = 0; int pdnDevInst1 = 0; int pulLen = 0; uint pdnDevInst2; if (DeviceDrivers.CM_Locate_DevNodeA(ref pdnDevInst1, deviceId, num1) != num2 || DeviceDrivers.CM_Get_Parent(out pdnDevInst2, (uint)pdnDevInst1, num1) != num2 || DeviceDrivers.CM_Get_Device_ID_Size(out pulLen, pdnDevInst2, num1) != num2) return false; char[] buffer = new char[pulLen]; if (DeviceDrivers.CM_Get_Device_ID(pdnDevInst2, buffer, pulLen, 0) != num2) return false; parentDeviceId = new string(buffer); return true; } catch (Exception ex) { return false; } }