How can I cycle a USB device from C#?

前端 未结 2 720
感动是毒
感动是毒 2020-12-13 17:08

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:

http://ww

2条回答
  •  爱一瞬间的悲伤
    2020-12-13 17:43

    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;
    }
    

提交回复
热议问题