Windows判断是否为管理员

// IsUserAdminTest.cpp : Defines the entry point for the console application.
//

#include <Windows.h>
#include <tchar.h>
#include <iostream>
BOOL IsUserAdmin();

int _tmain(int argc, _TCHAR* argv[])
{
	printf_s("%d\n",IsUserAdmin());
	return 0;
}

BOOL IsUserAdmin()
{
	BOOL b = FALSE;
	SID_IDENTIFIER_AUTHORITY NtAuthority = SECURITY_NT_AUTHORITY;
	PSID AdministratorsGroup = NULL; 
	b = AllocateAndInitializeSid(
		&NtAuthority,
		2,
		SECURITY_BUILTIN_DOMAIN_RID,
		DOMAIN_ALIAS_RID_ADMINS,
		0, 0, 0, 0, 0, 0,
		&AdministratorsGroup); 
	if(b) 
	{
		HANDLE hThreadUserToken = NULL;
		if (!::OpenThreadToken(::GetCurrentThread(), 
			TOKEN_READ,//must have TOKEN_QUERY
			false,
			&hThreadUserToken))
		{
			if (!CheckTokenMembership( hThreadUserToken, AdministratorsGroup, &b)) 
			{
				b = FALSE;
			}
			if (AdministratorsGroup)
			{
				FreeSid(AdministratorsGroup); 
			}
		}
		if (hThreadUserToken)
		{
			CloseHandle(hThreadUserToken);
		}
	}
	return(b);
}

  

posted @ 2014-09-15 11:21  2012harry  阅读(189)  评论(0编辑  收藏  举报