1. 程式人生 > >使用者是否是用管理員許可權執行本程序

使用者是否是用管理員許可權執行本程序

#include <windows.h>
#include <ShlObj.h>
#include <iostream>

using namespace std;

BOOL GetProcessElevation(TOKEN_ELEVATION_TYPE * pElevationType , BOOL * pIsAdmin)
{
	HANDLE hToken = NULL;
	DWORD dwSize;

	if ( !OpenProcessToken(GetCurrentProcess() , TOKEN_QUERY , &hToken) )
	{
		return FALSE;
	}

	BOOL bResult = FALSE;

	if ( GetTokenInformation(hToken , TokenElevationType , pElevationType , sizeof(TOKEN_ELEVATION_TYPE) , &dwSize) )
	{
		BYTE adminSID[SECURITY_MAX_SID_SIZE];
		dwSize = sizeof(adminSID);
		CreateWellKnownSid(WinBuiltinAdministratorsSid , NULL , &adminSID , &dwSize);

		if ( *pElevationType == TokenElevationTypeLimited )
		{
			HANDLE hUnfilteredToken = NULL;
			GetTokenInformation(hToken , TokenLinkedToken , (VOID*)hUnfilteredToken , sizeof(HANDLE) , &dwSize);

			if (CheckTokenMembership(hUnfilteredToken , &adminSID , pIsAdmin))
			{
				bResult = TRUE;
			}

			CloseHandle(hUnfilteredToken);
		}
		else
		{
			*pIsAdmin = IsUserAnAdmin();
			bResult = TRUE;
		}
	}

	CloseHandle(hToken);
	return bResult;
}

int _tmain(int argc, _TCHAR* argv[])
{
	TOKEN_ELEVATION_TYPE t;
	BOOL isAdmin = FALSE;
	BOOL bRunRight = GetProcessElevation(&t , &isAdmin);

	if (bRunRight)
	{
		if (isAdmin)
		{
			cout<<"是管理員"<<endl;
		}
		else
		{
			cout<<"不是管理員"<<endl;
		}
	}

	system("pause");

	return 0;
}