I am trying to run my app from start-up as an administrative. To do so I have written the below code:
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
System.Security.Principal.WindowsIdentity identity = System.Security.Principal.WindowsIdentity.GetCurrent();
System.Security.Principal.WindowsPrincipal principal = new System.Security.Principal.WindowsPrincipal(identity);
if (principal.IsInRole(System.Security.Principal.WindowsBuiltInRole.Administrator))
{
Application.Run(new HomePage());
}
else
{
System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();
startInfo.UseShellExecute = true;
startInfo.WorkingDirectory = Environment.CurrentDirectory;
startInfo.FileName = Application.ExecutablePath;
startInfo.Verb = "runas";
try
{
System.Diagnostics.Process.Start(startInfo);
Application.Exit();
}
catch
{
return;
}
Application.Exit();
}
Application.Run(new HomePage());
This is my program.cs file. The problem is when I run it it comes with two same application. I have tried many methods but I failed to solve it.
Is it possible to run my app as an admin from start-up without provoking the run as administrative dialogue?
You're calling application.run twice (once Inside the if if you're an administrator, and once after the if/else block) so for an administrator it will run twice.
Just remove the application.run after the if/else or invert your if else to say if not administrator (what you currently have in the else) , don't put an else and leave the application run at the end wich will only be hit if you're not administrator
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
System.Security.Principal.WindowsIdentity identity = System.Security.Principal.WindowsIdentity.GetCurrent();
System.Security.Principal.WindowsPrincipal principal = new System.Security.Principal.WindowsPrincipal(identity);
// If you're an administrator
if (principal.IsInRole(System.Security.Principal.WindowsBuiltInRole.Administrator))
{
// Then run the application (first time)
Application.Run(new HomePage());
}
else
{
System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();
startInfo.UseShellExecute = true;
startInfo.WorkingDirectory = Environment.CurrentDirectory;
startInfo.FileName = Application.ExecutablePath;
startInfo.Verb = "runas";
try
{
System.Diagnostics.Process.Start(startInfo);
Application.Exit();
}
catch
{
return;
}
Application.Exit();
}
// you end up here after it ran as an admin, skipping the else and you tell it to run again, either remove that line or invert your condition
Application.Run(new HomePage());
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.