In Vista and Windows 7 and later, a security mechanism called UAC (User Account Control) has been added, and if UAC is turned on, even if the user logs in with administrator privileges, their applications cannot write to the system directory, system registry, and other settings that may affect the normal operation of the system by default. This mechanism greatly enhances the security of the system, but for application developers, we cannot force users to turn off UAC, but sometimes the application we develop needs to run in the way of administrator, how to achieve such a function? Here's how a C# program implements prompting the user to run with administrator privileges. In this example, the WinForm program demonstrates that a new project is generated and modified accordingly: Method 1: Start via System.Diagnostics.Process.Start(): Implementation method: Modify the program file generated by default, and the modified code is as follows: Since the code has already been commented on, it will not go into details; Effect: Since it is started by calling the external call of System.Diagnostics.Process.Start(), when running directly through VS, it will not prompt VS to need administrator rights, only the program itself needs administrator rights, which is different from the program that generates the application. This is the main difference from the implementation of method 2. Method 2: By adding an application manifest file: On the Project Add New Item, select Application Manifest File and click the Add button Once added, the app.manifest file is opened by default, which will: Modified to: Then open the Project Properties and modify the Manifest in the Resources in the Applications tab to the new app.manifest. Rebuild the project, and when you open the program again, you will be prompted to run with administrator privileges. Note that if you start debugging in VS, you will be prompted that this task requires the application to have elevated privileges. As shown below: Select Restart with other credentials to do so. Method 3: Modify the properties of the program file directly Right-click on the program file in the Compatibility tab in the Properties dialog box that pops up Check "Run this program as administrator".
|