Installing a specific driver for a specific device programmatically (and when pre-install fails)

StackOverflow https://stackoverflow.com/questions/8565978

  •  21-03-2021
  •  | 
  •  

Question

I have a signed driver and I need to install it programmatically for a specific USB device using C# (targeting Vista and 7 64-bit).

I found very easy the use of the DriverPackagePreinstall function within the DIFx API (here is how to P/Invoke it): by calling it before the device is plugged into the USB, Windows is able to associate the driver to the device once this is detected.

The problems arise when the device is plugged into the USB without having pre-installed the driver. It can happen that another driver is installed for that device (in one test PC I found that a generic driver has been installed and that the device is listed under "Other devices" in Device Manager).

Trying to solve this problem, up to now I've been able to detect that the device is there by using the SetupDiGetClassDevs, the SetupDiEnumDeviceInfo and the SetupDiGetDeviceRegistryProperty functions in order to identify the device by its VID and PID (vendor and product identifier). Now that I have the SP_DEVINFO_DATA for my device I guess I've to call the InstallSelectedDriver function, isn't it? If yes, could you please tell me how to P/Invoke that function (I cannot find it on pinvoke.net) and how to use it by specifying the driver I want to install for my device (supposing I've the INF path)?

Was it helpful?

Solution

I found a sample for exactly what I was searching for here. The P/Invoke for InstallSelectedDriver works for me as:

[DllImport("newdev.dll", SetLastError = true, CharSet = CharSet.Auto)]
[return: MarshalAs(UnmanagedType.Bool)]
protected static extern bool InstallSelectedDriver(
      IntPtr HwndParent,
      IntPtr DeviceInfoSet,
      string Reserved,
      [MarshalAs(UnmanagedType.Bool)] bool Backup,
      out UInt32 Reboot);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top