/* * 删除指定的usb虚拟串口 * 输入值: 设备管理器下的设备名称,不包括后面的(COMXX) * 返回值: 成功/失败 */ /*!!!BUG: 删除port后重新扫描,port number会加一;插拔或者通过设备管理器Uninstall port没有这个问题。!!!*/ public static bool DeletePort(String portName = null) { bool ret = false; Guid classGuid = Guid.Empty; IntPtr hDevInfo = Win32.SetupDiGetClassDevs(ref classGuid, null, IntPtr.Zero, Win32.DIGCF_ALLCLASSES | Win32.DIGCF_PRESENT); if (hDevInfo.ToInt32() == Win32.INVALID_HANDLE_VALUE) { Console.WriteLine("访问硬件设备失败"); } else { int i = 0; int selected = 0; StringBuilder deviceName = new StringBuilder(); deviceName.Capacity = Win32.MAX_DEV_LEN; do { UsbRemoveHidden.Win32.SP_DEVINFO_DATA devInfoData = new UsbRemoveHidden.Win32.SP_DEVINFO_DATA(); StringBuilder _DeviceName = new StringBuilder(""); _DeviceName.Capacity = 1000; devInfoData.cbSize = Marshal.SizeOf(typeof(UsbRemoveHidden.Win32.SP_DEVINFO_DATA)); devInfoData.classGuid = Guid.Empty; devInfoData.devInst = 0; devInfoData.reserved = IntPtr.Zero; bool result = Win32.SetupDiEnumDeviceInfo(hDevInfo, i, devInfoData); if (false == result) { break; } Win32.SetupDiGetDeviceRegistryProperty(hDevInfo, devInfoData, 0, 0, _DeviceName, (uint)_DeviceName.Capacity, IntPtr.Zero); if (_DeviceName.ToString().Equals(portName)) { Debug.WriteLine("Log.Level.Operation," + _DeviceName.ToString() + ":" + Win32.GetDeviceInstanceId(hDevInfo, devInfoData).ToString()); selected = i; } ++i; } while (true); ret = Win32.Remove(selected, hDevInfo); } Win32.SetupDiDestroyDeviceInfoList(hDevInfo); return(ret); }
public static bool Remove(int SelectedItem, IntPtr DevInfo) { bool result = false; UsbRemoveHidden.Win32.SP_DEVINFO_DATA devInfoData = new UsbRemoveHidden.Win32.SP_DEVINFO_DATA(); devInfoData.cbSize = Marshal.SizeOf(typeof(SP_DEVINFO_DATA)); if (true == SetupDiEnumDeviceInfo(DevInfo, SelectedItem, devInfoData)) { if (true == SetupDiCallClassInstaller(Win32.DIF_REMOVE, DevInfo, devInfoData)) { result = true; } else { uint ret = (uint)Win32.GetLastError(); System.Diagnostics.Debug.WriteLine("Operation, Remove Device failed(" + ret.ToString() + ")"); } } return(result); }