1

I want to ask for local administrator permission when pressing a button.

I'm intending to pop up an UAC prompt to ask for it.

I don't want to make the program only be ran as an administrator so I don't think I want to add an application manifest.

I tried to use a Process.Start() on the executable with Verb = "runas", which pops up the UAC prompt, but that ends up running another copy of the application.

private void button1_Click(object sender, EventArgs e)
{ 
    ProcessStartInfo startInfo = new ProcessStartInfo
    {
        FileName = Application.ExecutablePath,
        Verb = "runas"
    };
    Process.Start(startInfo);
    if(//permission granted)
    {
        //code
    }
    else
    {
        MessageBox.Show("Permission not granted");
    }
}

I also tried to use PrincipalPermissions class but didn't call the prompt I wanted to.

  • 2
    You are correct. A *process* runs as a particular user - you can't run part of a process as one user, and part as another user. If you want your application to start as one user, but then elevate to another user, then you need to start a new process. – canton7 Feb 19 '19 at 12:02
  • related, maybe duplicated: https://stackoverflow.com/questions/133379/elevating-process-privilege-programmatically – Cleptus Feb 19 '19 at 12:04
  • @bradbury9 I don't want to necessarily use Process.Start(), it's just one way I tried to make the UAC prompt pop up. If there's any other way I would use it instead of Process class. – Diogo Almeida Feb 19 '19 at 12:08
  • I would consider adding an executable argument to control whenever the second execution was called under higher privileges. If that were received you could choose not to start any form but just do your privileged logic. – Cleptus Feb 19 '19 at 12:09
  • @DiogoAlmeida Check the answers of that question, they mention also SecurityDemand and things like that. Edit: [this answer](https://stackoverflow.com/a/8832162/2265446) could be useful – Cleptus Feb 19 '19 at 12:10
  • @bradbury9 Can you reference me an article related to your comment or explain it in a simpley way? Sorry, I'm quite green in programming. – Diogo Almeida Feb 19 '19 at 12:16
  • @bradbury9 I have actually referenced to that answer, but I want to make the method accessible from a normal user account and executed when granted the administrator permission – Diogo Almeida Feb 19 '19 at 12:19
  • [This](https://learn.microsoft.com/en-us/windows/desktop/uxguide/winenv-uac) is a good starting point and [this one](https://learn.microsoft.com/en-us/cpp/security/how-user-account-control-uac-affects-your-application?view=vs-2017) is a more technical one. – Cleptus Feb 19 '19 at 12:22
  • @bradbury9 I did get what those articles consisted and how UAC is used but, sorry to ask, what do you mean with "adding an executable argument to control whenever the second execution was called under higher privileges" – Diogo Almeida Feb 19 '19 at 12:41

0 Answers0