Run Process as Administrator from a Non-Admin Application

Run process as administrator from a non-admin application

You must use ShellExecute. ShellExecute is the only API that knows how to launch Consent.exe in order to elevate.

Sample (.NET) Source Code

In C#, the way you call ShellExecute is to use Process.Start along with UseShellExecute = true:

private void button1_Click(object sender, EventArgs e)
{
//Public domain; no attribution required.
ProcessStartInfo info = new ProcessStartInfo(@"C:\Windows\Notepad.exe");
info.UseShellExecute = true;
info.Verb = "runas";
Process.Start(info);
}

If you want to be a good developer, you can catch when the user clicked No:

private void button1_Click(object sender, EventArgs e)
{
//Public domain; no attribution required.
const int ERROR_CANCELLED = 1223; //The operation was canceled by the user.

ProcessStartInfo info = new ProcessStartInfo(@"C:\Windows\Notepad.exe");
info.UseShellExecute = true;
info.Verb = "runas";
try
{
Process.Start(info);
}
catch (Win32Exception ex)
{
if (ex.NativeErrorCode == ERROR_CANCELLED)
MessageBox.Show("Why you no select Yes?");
else
throw;
}
}

Bonus Watching

  • UAC - What. How. Why.. The architecture of UAC, explaining that CreateProcess cannot do elevation, only create a process. ShellExecute is the one who knows how to launch Consent.exe, and Consent.exe is the one who checks group policy options.

How do I start a process with administrator privileges without my WPF host also runs with admin rights in order to implement file drag & drop?

First, if you need to run just one operation which requires admin rights - that does not mean your whole application should run with admin rights. You need to evelate only for this particular operation. Easiest way to do this is setting UseShellExecute = true when starting your process - then Windows will show usual UAC prompt to user, so that he can confirm evelation. You can describe situation to user before that (in some dialog), or you can put usual UAC icon on button that performs that action (that shield icon).

If that is not an option for you (for example you need redirected output) - you can run another copy of your own application with certain arguments with admin rights (exactly as described above, but not wevtutil, but your own application). This evelated copy will only run wevtutil and exit, doing nothing more.



Related Topics



Leave a reply



Submit