How can I cycle a USB device from C#?

拟墨画扇 提交于 2019-11-28 18:28:21

Got it working by using a commandline tool called devcon, which I then called from code.

Dropped devcon.exe into one of the system paths so it works everywhere.

Devcon: devcon

called: DEVCON Remove *usb"*MI_01"

then called: 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();

You can use the C# Hardware Helper Lib and add the ResetDevice function.

Just make sure you add

public const int DICS_PROPCHANGE = ((0x00000003)); 

at the public class Native under //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;
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!