Using external function CheckTokenMembership in the below example from SO, I get access errors after the function IsUserAdmin returns to IsUserAdminStr.
When b is local var to n then there will be an access violation immediately after IsUserAdmin. If b is global var then it works.
Removing CheckTokenMembership
stops error. FreeSid(AdministratorsGroup)
has no effect. Changing to Result := true;
has no effect
Please, please point out what I am so obviously missing.
//from https://stackoverflow.com/questions/6261865/looking-for-delphi-7-code-to-detect-if-a-program-is-started-with-administrator-r
//var b:boolean; // <------ Works if b is here
function IsUserAdminStr(SingleChar:boolean=false):string;
begin
if IsUserAdmin
then result:='Admin'
else result:='User'; //<----------- throws access error here
end;
function CheckTokenMembership(TokenHandle: THandle; SIdToCheck: PSID; var IsMember: Boolean): BOOL; StdCall; External AdvApi32;
function IsUserAdmin: Boolean;
var
b: boolean; // <-----------Fails if b is here
b: BOOL; // <------- this works
AdministratorsGroup: PSID;
const
SECURITY_NT_AUTHORITY: SID_IDENTIFIER_AUTHORITY =
(Value: (0,0,0,0,0,5)); // ntifs
SECURITY_BUILTIN_DOMAIN_RID: DWORD = $00000020;
DOMAIN_ALIAS_RID_ADMINS: DWORD = $00000220;
begin
b := AllocateAndInitializeSid(
SECURITY_NT_AUTHORITY,
2, //2 sub-authorities
SECURITY_BUILTIN_DOMAIN_RID, //sub-authority 0
DOMAIN_ALIAS_RID_ADMINS, //sub-authority 1
0, 0, 0, 0, 0, 0, //sub-authorities 2-7 not passed
AdministratorsGroup);
if (b) then
begin
if not CheckTokenMembership(0, AdministratorsGroup, b) then
b := False;
FreeSid(AdministratorsGroup);
end;
Result := b;
end;