gpt4 book ai didi

delphi - 如何使用 Lazarus/Free Pascal 获取 Windows 用户权限信息

转载 作者:行者123 更新时间:2023-12-01 23:22:00 31 4
gpt4 key购买 nike

使用 Lazarus/Free Pascal,我如何获得运行我的程序的用户的用户权限(无论他是管理员、普通用户还是 guest )?

最佳答案

正如 David 在评论中所说,您可以使用 CheckTokenMembership函数来确定用户帐户的成员资格。

检查这个在 FPC 和 Delphi 上运行的示例。

program Test;

{$IFDEF FPC}
{$mode objfpc}{$H+}
{$ELSE}
{$APPTYPE CONSOLE}
{$ENDIF}

uses
SysUtils,
Windows,
Classes;

Const
SECURITY_NT_AUTHORITY: TSIDIdentifierAuthority = (Value: (0, 0, 0, 0, 0, 5));
SECURITY_BUILTIN_DOMAIN_RID = $00000020;
DOMAIN_ALIAS_RID_ADMINS = $00000220;
DOMAIN_ALIAS_RID_USERS = $00000221;
DOMAIN_ALIAS_RID_GUESTS = $00000222;
DOMAIN_ALIAS_RID_POWER_USERS= $00000223;

function CheckTokenMembership(TokenHandle: THandle; SidToCheck: PSID; var IsMember: BOOL): BOOL; stdcall; external advapi32;

function UserInGroup(Group :DWORD) : Boolean;
var
pIdentifierAuthority :TSIDIdentifierAuthority;
pSid : Windows.PSID;
IsMember : BOOL;
begin
pIdentifierAuthority := SECURITY_NT_AUTHORITY;
Result := AllocateAndInitializeSid(pIdentifierAuthority,2, SECURITY_BUILTIN_DOMAIN_RID, Group, 0, 0, 0, 0, 0, 0, pSid);
try
if Result then
if not CheckTokenMembership(0, pSid, IsMember) then //passing 0 means which the function will be use the token of the calling thread.
Result:= False
else
Result:=IsMember;
finally
FreeSid(pSid);
end;
end;


begin
Writeln(Format('Current user is Admin %s',[BoolToStr(UserInGroup(DOMAIN_ALIAS_RID_ADMINS),True)]));
Writeln(Format('Current user is Guest %s',[BoolToStr(UserInGroup(DOMAIN_ALIAS_RID_GUESTS),True)]));
Writeln(Format('Current user is Power User %s',[BoolToStr(UserInGroup(DOMAIN_ALIAS_RID_POWER_USERS),True)]));
readln;
end.

您也可以使用 WMI ,检查 Win32_UserAccount , Win32_GroupUserWin32_Group类。

关于delphi - 如何使用 Lazarus/Free Pascal 获取 Windows 用户权限信息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8288525/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com