如何从 C# 循环 USB 设备?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/916296/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I cycle a USB device from C#?
提问by callisto
I'd like to cycle (simulate unplug and re-inserting) a USB device (modem) after a certain event has fired. I found a sample on codeproject:
我想在某个事件触发后循环(模拟拔出并重新插入)USB 设备(调制解调器)。我在 codeproject 上找到了一个示例:
That allows me to identify+eject the device via its non-volatile serial, but I need it to recycle, not just eject.
这使我可以通过其非易失性序列识别+弹出设备,但我需要它来回收,而不仅仅是弹出。
I have read this:
我读过这个:
I do not understand it.
我不明白。
This has been mentioned in other USB related posts:
这已在其他 USB 相关帖子中提到:
It is not relevant to my problem.
它与我的问题无关。
采纳答案by callisto
Got it working by using a commandline tool called devcon, which I then called from code.
通过使用名为 devcon 的命令行工具使其工作,然后我从代码中调用它。
Dropped devcon.exe into one of the system paths so it works everywhere.
将 devcon.exe 放入系统路径之一,因此它可以在任何地方使用。
Devcon: devcon
开发者大会:开发者大会
called: DEVCON Remove *usb"*MI_01"
调用:DEVCON Remove *usb"*MI_01"
then called: DEVCON rescan
然后调用:DEVCON rescan
code:
代码:
System.Diagnostics.Process proc = new System.Diagnostics.Process();
proc.StartInfo.FileName = "DEVCON";
proc.StartInfo.Arguments = "Remove *usb"*MI_01";
proc.StartInfo.RedirectStandardError = true;
proc.StartInfo.RedirectStandardOutput = true;
proc.StartInfo.UseShellExecute = false;
proc.Start();
回答by shahar_m
You can use the C# Hardware Helper Liband add the ResetDevice function.
您可以使用C# Hardware Helper Lib并添加ResetDevice 函数。
Just make sure you add
只要确保你添加
public const int DICS_PROPCHANGE = ((0x00000003));
at the public class Native
under //PARMS,
在public class Native
//PARMS下,
public bool ResetDevice( IntPtr hDevInfo, IntPtr devInfoData )
{
int szOfPcp;
IntPtr ptrToPcp;
int szDevInfoData;
IntPtr ptrToDevInfoData;
Native.SP_PROPCHANGE_PARAMS pcp = new Native.SP_PROPCHANGE_PARAMS();
pcp.ClassInstallHeader.cbSize = Marshal.SizeOf(typeof(Native.SP_CLASSINSTALL_HEADER));
pcp.ClassInstallHeader.InstallFunction = Native.DIF_PROPERTYCHANGE;
pcp.StateChange = Native.DICS_PROPCHANGE; // for reset
pcp.Scope = Native.DICS_FLAG_CONFIGSPECIFIC;
pcp.HwProfile = 0;
szOfPcp = Marshal.SizeOf(pcp);
ptrToPcp = Marshal.AllocHGlobal(szOfPcp);
Marshal.StructureToPtr(pcp, ptrToPcp, true);
szDevInfoData = Marshal.SizeOf(devInfoData);
ptrToDevInfoData = Marshal.AllocHGlobal(szDevInfoData);
Marshal.StructureToPtr(devInfoData, ptrToDevInfoData, true);
bool rslt1 = Native.SetupDiSetClassInstallParams(hDevInfo, ptrToDevInfoData, ptrToPcp, Marshal.SizeOf(typeof(Native.SP_PROPCHANGE_PARAMS)));
bool rstl2 = Native.SetupDiCallClassInstaller(Native.DIF_PROPERTYCHANGE, hDevInfo, ptrToDevInfoData);
if (rslt1 && rstl2)
{
return true;
}
return false;
}