Run process as administrator from a non-admin application

前端 未结 1 1643
轻奢々
轻奢々 2020-11-28 07:56

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

ProcessStartInfo proc = new ProcessStartInfo();
proc.WindowStyle = Pro         


        
相关标签:
1条回答
  • 2020-11-28 07:58

    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)
    {
       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)
    {
       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.

    Note: Any code released into public domain. No attribution required.

    0 讨论(0)
提交回复
热议问题