Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
695 views
in Technique[技术] by (71.8m points)

c# - Run process as administrator from a non-admin application

From an application that is not being run as administrator, I have the following code:

ProcessStartInfo proc = new ProcessStartInfo();
proc.WindowStyle = ProcessWindowStyle.Normal;
proc.FileName = myExePath;
proc.CreateNoWindow = false;
proc.UseShellExecute = false;
proc.Verb = "runas";

When I call Process.Start(proc), I do not get a pop up asking for permission to run as administrator, and the exe is not run as administrator.

I tried adding an app.manifest to the executable found at myExePath, and updated the requestedExecutionLevel to

<requestedExecutionLevel level="requireAdministrator" uiAccess="false" />

With the updated app.manifest, on the Process.Start(proc) call, I get an exception, "The requested operation requires elevation."

Why isn't the .Verb action not setting administrator privileges?

I am testing on Windows Server 2008 R2 Standard.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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:WindowsNotepad.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:WindowsNotepad.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.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...