How to elevate privileges only when required?

Hemant picture Hemant · Feb 21, 2009 · Viewed 79.4k times · Source

This question applies to Windows Vista!

I have an application which normally works without administrative privileges. There is one activity which does need administrative privilege but I don't want to start the application itself with higher privileges when I know most of time user wont even be using that feature.

I am thinking about certain method by which I can elevate the privileges of application on some event (such as press of a button). Example:

If user clicks this button then he is prompted with UAC dialog or consent. How can I do this?

Answer

Noldorin picture Noldorin · Feb 21, 2009

I don't believe that it is possible to elevate the currently running process. It is built into Windows Vista that administrator privileges are given to a process upon startup, as I understand. If you look at various programs that utilise UAC, you should see that they actually launch a separate process each time an administrative action needs to be performed (Task Manager is one, Paint.NET is another, the latter being a .NET application in fact).

The typical solution to this problem is to specify command line arguments when launching an elevated process (abatishchev's suggestion is one way to do this), so that the launched process knows only to display a certain dialog box, and then quit after this action has been completed. Thus it should hardly be noticeable to the user that a new process has been launched and then exited, and would rather appear as if a new dialog box within the same app has been opened (especially if you some hackery to make the main window of the elevated process a child of the parent process). If you don't need UI for the elevated access, even better.

For a full discussion of UAC on Vista, I recommend you see this very through article on the subject (code examples are in C++, but I suspect you'll need to use the WinAPI and P/Invoke to do most of the things in C# anyway). Hopefully you now at least see the right approach to take, though designing a UAC compliant program is far from trivial...