VB6 Code to check if User needs to "Run As Administrator"

5.4k views Asked by At

Several users of my visual basic 6 application must "run as administrator" Others, do not and can just double click.

Is there a code that I can add as the program opens to check if Run As Aministrator is necessary and then open a window to indicate this?

2

There are 2 answers

2
Ahmad On

You will need to use an API to determine if the current user has administrative rights or not.

Luckily, there is one function that returns 0 for False to indicate the status of the current user. Namely: IsUserAnAdmin

Here is how to declare it and use it:

'In a module file:
Public Declare Function IsUserAnAdmin Lib "Shell32" Alias "#680" () As Integer

Then in your Form_Load()

Sub Form_Load()

   If IsUserAnAdmin() = 0 Then 
     MsgBox "Not admin" 
   Else 
     MsgBox "Admin" 
   End If

End Sub

Note: The Shell function IsUserAnAdmin is depricated. You can replace the functionality with something like (pseudocode):

Boolean IsUserAdmin()
{
   PSID administratorsGroup = StringToSid("S-1-5-32-544"); //well-known Administrators group

   Boolean isAdmin;
   if (not CheckTokenMembership(0, administratorsGroup, out isAdmin) then
      isAdmin = false;

   FreeSid(administratorsGroup);

   return isAdmin;
}
0
Bob77 On

Just add the proper "level" value to the application manifest.

Sample manifest fragment:

<trustInfo xmlns="urn:schemas-microsoft-com:asm.v3">
    <security>
        <requestedPrivileges>
            <requestedExecutionLevel level="requireAdministrator"
                                     uiAccess="false"/>
        </requestedPrivileges>
    </security>
</trustInfo> 

This causes Windows to raise the UAC prompt without any special action by the user and without any added code. Now that Windows XP is dead and buried this works in all supported versions of Windows except lingering remnants of Windows Server 2003 which are scheduled to leave extended support in a matter of months.