Elevating EXEs in Windows Vista with UAC on

Posted: (EET/GMT+2)

 

Windows Vista gives you two options for elevation: you can either start another process (EXE) with elevated rights ("admin rights") or you can invoke a COM object with a so-called elevation moniker. Now, sometimes you just want to launch a process elevated, the same way as you can right-click for instance a shortcut on Vista, and select "Run as Administrator" from the popup menu. But how would you do the same programmatically?

The answer is the familiar ShellExecute API function, which supports certain verbs, such as "open", "print" and "find". With Vista, it also supports a new verb called "runas", which is precisely what you need. If you use the "runas" verb, the screen will go blank, and the user is prompted for his or her concent for the operation. You cannot programmatically override or skip this step, it is how Vista works. Similarly, you cannot use CreateProcess API for this task. Here's an example code with C#:

using System.Runtime.InteropServices;
...
public const int SW_SHOWNORMAL = 1;     
[DllImport("shell32.dll")]
static extern IntPtr ShellExecute(
  IntPtr hwnd,
  string lpOperation,
  string lpFile,
  string lpParameters,
  string lpDirectory,
  int nShowCmd);
...
private void launchNotepadButton_Click(object sender, EventArgs e)
{
  ShellExecute(this.Handle, "runas", "notepad.exe", "", "", SW_SHOWNORMAL);
}

In this example, Notepad is launched, but of course the process could be any process you lile. Note also that the MSDN documentation of ShellExecute is not yet up to date, but will soon be.