What's the proper way to run a piece of code with admin privileges conditionally?

43 Views Asked by At

I am developing a C#/.NET/AvaloniaUI application that communicates with a USB device over libusb. This requires the WinUSB driver to be paired with the device on Windows. Most users in my use case will already have this driver paired to this USB ID, but some won't. I would like to use libwdi to notice this and install the driver automatically, but only do that for that small portion of users, and only the first time. But as one would expect, pairing a USB device to a driver requires admin privileges.

So ideally, the app would realize it needs admin privileges, show a popup that says "I'm going to need admin privileges to be able to do X", then prompt the user to grant them, much like an installer.

But, after a process is launched in Windows, the privileges it runs with can't be changed, as far as I understand. What's the proper way to get around this ?

I get that it's possible to launch a different process and ask the user to grant admin rights to that one via runas, but bundling a separate executable and passing it all the contextual information sounds very inconvenient. I was honestly thinking of straight up outputting the C# code to a separate file and dotnet runing it... but surely there's a better way ?

1

There are 1 best solutions below

0
Ian Boyd On

When you need to do the thing that requires an adminstrator:

  • launch your application again using ShellExecute with the runas verb
  • Pass a /doTheThing command line paramter

Your application checks on startup if the /doTheThing command line paramters was passed, and if so jump straight into doing the thing. Then exit.

And you create a button somewhere with the IDI_SHIELD on it, so that users will know that clicking it will cause a UAC prompt to appear.

You NEVER want a UAC prompt to appear randomly without apparent cause. It should always, always, always be in specific response to a user clicking a UAC shield.

enter image description here