I have discovered how to ask for administrator rights at runtime.
Here's how to do it: add this class to your Program.cs
file (alternatively, create standalone static bool)
public static class RequestAdministrator
{
public static bool request = false;
}
Now you want to check at startup, if your program has been ran with any arguments.
static void Main(string[] args)
{
if (args.Count() == 0 /* or args[0].ToString() == "admin"*/)
{
RequestAdministrator.request = false;
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
else
{
// request admin
RequestAdministrator.request = true;
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
}
And then place this code wherever you want your program to request admin rights. It restarts the program with "admin" argument, allowing you to put additional code in the if statement (e.g. load the same file from previous instance)
//this will try to get the administrator rights if the user is an admin
System.AppDomain.CurrentDomain.SetPrincipalPolicy(PrincipalPolicy.WindowsPrincipal)
if (IsAdministrator() == false)
{
//Init a new instance of the program
ProcessStartInfo startInfo = new ProcessStartInfo(System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName, "admin");
startInfo.UseShellExecute = true;
startInfo.Verb = "runas";
System.Diagnostics.Process.Start(startInfo);
//no need for Application.Exit()
}
public static bool IsAdministrator()
{
var identity = WindowsIdentity.GetCurrent();
var principal = new WindowsPrincipal(identity);
return principal.IsInRole(WindowsBuiltInRole.Administrator);
}
In the end, you can use this code to see if the admin right have been requested (you can use IsAdministrator()
as well to determine if user declined admin privileges)
if (RequestAdministrator.request == false)
{
// continue without rights (user ran the exe)
// your code here
// Step1 step1 = new Step1();
// this.Controls.Add(step1);
// step1.Show();
}
else
{
// request true (restarted with arguments)
// your code here
// Step2 step2 = new Step2();
// this.Controls.Add(step2);
// step2.Show();
}
Result
program asking for admin