我正在尝试在 Windows 安装项目期间安装驱动程序。
我要做的第一步是复制 INF 文件并预安装驱动程序。
SetupCopyOEMInf(infFile, null, 1, 0, null, 0, 0, null);
这会正确预安装驱动程序,但在设备管理器中完成硬件重新扫描之前,设备无法使用。我也想自动化这个。我曾尝试使用setupapi.dll 来调用硬件重新扫描,但对我来说并不总是成功。使用 devcon.exe rescan 总是强制重新扫描硬件,但它是一个同步命令,它在设备完成安装之前返回。硬件扫描完成并成功安装驱动后,有什么方法可以得到返回结果?
谢谢,
米莎
编辑
这是我的工作代码:
public const UInt32 CR_SUCCESS = 0;
public const UInt64 CM_REENUMERATE_SYNCHRONOUS = 1;
public const UInt64 CM_LOCATE_DEVNODE_NORMAL = 0;
[DllImport("setupapi.dll")]
public static extern bool SetupCopyOEMInf(
string SourceInfFileName,
string OEMSourceMediaLocation,
int OEMSourceMediaType,
int CopyStyle,
string DestinationInfFileName,
int DestinationInfFileNameSize,
int RequiredSize,
string DestinationInfFileNameComponent
);
[DllImport("cfgmgr32.dll")]
public static extern int CM_Locate_DevNode_Ex(ref IntPtr deviceHandle, int deviceId, uint flags, IntPtr machineHandle);
[DllImport("cfgmgr32.dll")]
public static extern int CM_Reenumerate_DevNode_Ex(IntPtr devInst, UInt64 flags);
[DllImport("cfgmgr32.dll")]
public static extern int CMP_WaitNoPendingInstallEvents(UInt32 timeOut);
static void Main() {
bool success = SetupCopyOEMInf(infFile, null, 1, 0, null, 0, 0, null);
if(!success) {
throw new Exception("Error installing driver");
}
success = RescanAllDevices();
if (!success) {
throw new Exception("Error installing driver");
}
}
public static bool RescanAllDevices() {
int ResultCode = 0;
IntPtr LocalMachineInstance = IntPtr.Zero;
IntPtr DeviceInstance = IntPtr.Zero;
UInt32 PendingTime = 30000;
ResultCode = CM_Locate_DevNode_Ex(ref DeviceInstance, 0, 0, LocalMachineInstance);
if (CR_SUCCESS == ResultCode) {
ResultCode = CM_Reenumerate_DevNode_Ex(DeviceInstance, CM_REENUMERATE_SYNCHRONOUS);
ResultCode = CMP_WaitNoPendingInstallEvents(PendingTime);
}
return ResultCode == CR_SUCCESS;
}