For program programming in Vista/win7, we usually pay attention to two issues: "Does my program really have administrator permissions ?", "How does my program implement permission switching ?".
These two problems have been bothering me for a long time. Finally, I found the answer on codeproject. Now I will share it with you.
First, let's see how to check whether your program is administrator privilege. This code is relatively simple. (Special thanks to hackman3vilguy fromcodeproject)
Using system. Security. Principal;
/// <Summary>
/// Checks if the process is elevated
/// </Summary>
/// <Returns> If is elevated </returns>
Static internal bool isadmin ()
{
Windowsidentity id = windowsidentity. getcurrent ();
Windowsprincipal P = new windowsprincipal (ID );
Return P. isinrole (windowsbuiltinrole. Administrator );
}
This code returns a bool variable. If it is true, the program also has the admin permission under UAC. Otherwise, it is in restricted mode.
We often see that the program requesting admin under UAC has a small shield, proving that this program requires admin permission. So how can I add a UAC tag to my button to implement permission switching? You need to import an API function.
Public static class vistasecurity
{
[Dllimport ("USER32")]
Public static extern uint32 uparam message (intptr hwnd, uint32 MSG, uint32 wparam, uint32 lparam );
Internal const int bcm_first = 0x1600;
Internal const int bcm_setshield = (bcm_first + 0x000c );
/// <Summary>
/// Add a shield icon to a button
/// </Summary>
/// <Param name = "B"> the button </param>
Static internal void addshieldtobutton (Button B)
{
B. flatstyle = flatstyle. system;
Sendmessage (B. Handle, bcm_setshield, 0, 0 xffffffff );
}
After the button receives the message, it will automatically mark itself, so you don't have to worry about it. This is the benefit of the API.
The code below is to implement the UAC Program permission switch --
/// <Summary>
/// Restart the current process with Administrator Credentials
/// </Summary>
Internal static void restartelevated ()
{
Processstartinfo startinfo = new processstartinfo ();
Startinfo. useshellexecute = true;
Startinfo. workingdirectory = environment. currentdirectory;
Startinfo. filename = application. executablepath;
Startinfo. verb = "RunAs ";
Try
{
PROCESS p = process. Start (startinfo );
}
Catch (system. componentmodel. win32exception ex)
{
Return; // if canceled, do nothing
}
Application. Exit ();
}
By adding "RunAs" information to the verb in processstartinfo, you can switch the permissions of the program. Here, I am using the method that has obtained the permission to restart the program. If you do not want to restart the program, you can transmit arguments, or, you can only upgrade a thread to execute the Administrator code (???) without improving the program permissions (????).