从非管理员应用程序以管理员身份运行流程

jkh*_*jkh 29 c# uac processstartinfo runas

从未以管理员身份运行的应用程序,我有以下代码:

ProcessStartInfo proc = new ProcessStartInfo();
proc.WindowStyle = ProcessWindowStyle.Normal;
proc.FileName = myExePath;
proc.CreateNoWindow = false;
proc.UseShellExecute = false;
proc.Verb = "runas";
Run Code Online (Sandbox Code Playgroud)

当我调用Process.Start(proc)时,我没有弹出请求以管理员身份运行的权限,并且exe不以管理员身份运行.

我尝试将app.manifest添加到myExePath中找到的可执行文件,并将requestedExecutionLevel更新为

<requestedExecutionLevel level="requireAdministrator" uiAccess="false" />
Run Code Online (Sandbox Code Playgroud)

使用更新的app.manifest,在Process.Start(proc)调用中,我得到一个异常,"请求的操作需要提升."

为什么.Verb操作没有设置管理员权限?

我正在测试Windows Server 2008 R2 Standard.

Ian*_*oyd 50

必须使用ShellExecute.ShellExecute是唯一知道如何启动Consent.exe以提升的API .

示例(.NET)源代码

在C#中,你可以调用的方法ShellExecute是使用Process.Start连同UseShellExecute = true:

private void button1_Click(object sender, EventArgs e)
{
   ProcessStartInfo info = new ProcessStartInfo(@"C:\Windows\Notepad.exe");
   info.UseShellExecute = true;
   info.Verb = "runas";
   Process.Start(info);
}
Run Code Online (Sandbox Code Playgroud)

如果你想成为一名优秀的开发人员,你可以在用户点击No时捕获:

private void button1_Click(object sender, EventArgs e)
{
   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;
   }
}
Run Code Online (Sandbox Code Playgroud)

奖金观看

  • UAC - 什么.怎么样.为什么..UAC的体系结构,解释说CreateProcess无法进行提升,只创建一个进程.ShellExecute是知道如何启动Consent.exe的人,而Consent.exe是检查组策略选项的人.

注意:任何代码都会发布到公共领域.无需归属.