Comment puis-je parcourir un périphérique USB de C #?
-
06-09-2019 - |
Question
Je voudrais cycle (simuler en débranchant et réinsérant) un périphérique USB (modem) après un certain événement a tiré. J'ai trouvé un échantillon sur CodeProject:
Cela me permet d'identifier + éjecter le périphérique via sa série non volatile, mais je dois à recycler, et pas seulement d'éjection.
J'ai lu ceci:
Je ne comprends pas.
Cela a été mentionné dans d'autres postes liés à l'USB:
Il est pas pertinent à mon problème.
La solution
Vous avez fonctionner à l'aide d'un outil de ligne de commande appelé DevCon, que je puis appelé à partir du code.
Laissé tomber devcon.exe dans l'un des chemins du système de sorte qu'il fonctionne partout.
Devcon: devcon
appelé: DEVCON Supprimer * usb "* MI_01"
alors appelé: 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();
Autres conseils
Vous pouvez utiliser le C # Hardware Helper Lib et ajoutez le fonction ResetDevice .
Assurez-vous d'ajouter
public const int DICS_PROPCHANGE = ((0x00000003));
au public class Native
sous // 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;
}