在Win7中,我们有时需要判断哪些进程是以管理员权限运行的,有时需要判断该进程是服务进程还是用户进程。下面这段代码可以实现在Win7中获取一个以管理员权限运行的客户进程。
BOOL FindUacToken(HANDLE &hToken)
{HANDLE hProcessSnap = NULL;
BOOL bRet = FALSE;
PROCESSENTRY32 pe32 = {0};
hProcessSnap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
if (hProcessSnap == INVALID_HANDLE_VALUE)
return FALSE;
pe32.dwSize = sizeof(PROCESSENTRY32);
hToken = NULL;
if (Process32First(hProcessSnap, &pe32))
{
do
{
HANDLE hProcess = OpenProcess(PROCESS_QUERY_INFORMATION, FALSE, pe32.th32ProcessID);
if (OpenProcessToken(hProcess, TOKEN_ALL_ACCESS, &hToken))
{
DWORD TokenIsElevated;
DWORD dwReturnLength = 0;
// 获取进程信息,以判断是否以管理员权限运行
if (GetTokenInformation(hToken, (_TOKEN_INFORMATION_CLASS)20,&TokenIsElevated,sizeof(DWORD),&dwReturnLength))
{
if (dwReturnLength == sizeof(DWORD) && 1 == TokenIsElevated) // 说明是以管理员权限运行的
{
UCHAR InfoBuffer[ 512 ];
DWORD cbInfoBuffer = 512;
DWORD cchUser;
DWORD cchDomain;
TCHAR UserName[128];
TCHAR DomainName[128];
SID_NAME_USE snu;
// 再次 获取进程信息,以判断是否是用户进程
if ( GetTokenInformation(hToken, TokenUser, InfoBuffer, cbInfoBuffer, &cbInfoBuffer) )
{
bRet = LookupAccountSid(NULL, ((PTOKEN_USER)InfoBuffer)->User.Sid, UserName, &cchUser, DomainName, &cchDomain, &snu);
_tcslwr_s(UserName, 128);
_tcslwr_s(DomainName, 128);
if (NULL == _tcsstr(UserName, TEXT("system")) && NULL != _tcsstr(DomainName, TEXT("-pc")))
{
return TRUE;
}
}
}
}
CloseHandle(hToken);
}
CloseHandle(hProcess);
} while (Process32Next(hProcessSnap, &pe32));
}
else
{
bRet = FALSE;
}
CloseHandle (hProcessSnap);
return bRet;
}