C runs the program implementation code as an administrator by default
- 2020-11-25 07:13:31
- OfStack
In my last blog, I wrote about how to update the system time through network time, and how I failed to test it when I wrote it. Later, I wondered if it was my operating system (which was developed on win8 at that time). At that time, I guessed that the system time could not be modified due to insufficient permissions, so I ran it once as an administrator, and the test was successful! The original is really the issue of permissions, so in the program to add the default as an administrator to run the code. Let's see how it works!
The program runs as an administrator by default
Open the Program.cs file in the assembly and replace the code in the Main method with the above code to run the program as administrator by default.
This blog should have been published long ago, but due to the network and other reasons, 1 has not been published until now, the network problem will be solved soon, will continue to restore to the weekly update frequency, I hope you continue to pay attention to.
The program runs as an administrator by default
static void Main(string[] Args)
{
/**
* Launch the application directly when the current user is an administrator
* If you are not an administrator, start the program with a startup object to ensure that you are running as an administrator
*/
// Get the currently logged in Windows Users sign
System.Security.Principal.WindowsIdentity identity = System.Security.Principal.WindowsIdentity.GetCurrent();
// create Windows User theme
Application.EnableVisualStyles();
System.Security.Principal.WindowsPrincipal principal = new System.Security.Principal.WindowsPrincipal(identity);
// Determines whether the current logged in user is an administrator
if (principal.IsInRole(System.Security.Principal.WindowsBuiltInRole.Administrator))
{
// If it is an administrator, run it directly
Application.EnableVisualStyles();
Application.Run(new Form1());
}
else
{
// Create the launch object
System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();
// Setup run file
startInfo.FileName = System.Windows.Forms.Application.ExecutablePath;
// Set startup parameters
startInfo.Arguments = String.Join(" ", Args);
// Set startup action , Be sure to run as an administrator
startInfo.Verb = "runas";
// If you are not an administrator, start UAC
System.Diagnostics.Process.Start(startInfo);
// exit
System.Windows.Forms.Application.Exit();
}
}
Open the Program.cs file in the assembly and replace the code in the Main method with the above code to run the program as administrator by default.
This blog should have been published long ago, but due to the network and other reasons, 1 has not been published until now, the network problem will be solved soon, will continue to restore to the weekly update frequency, I hope you continue to pay attention to.