C++:判断进程是否”以管理员身份运行”

判断进程是否”以管理员身份运行”
https://hellokandy.blog.csdn.net/article/details/52097578

该代码无法在高版本编译器直接编译通过,简单改一下:



/// @brief		判断进程是否以管理员身份运行
	/// @param[in]	dwProcessId : 进程ID
	/// @param[in]	bCurrentProcess : 是否是当前进程
	///	@remark		bCurrentProcess为true时,dwProcessId无效
	///	@return		是管理员身份则返回true
bool IsRunAsAdministrator(DWORD dwProcessId, bool bCurrentProcess)
{
	bool bIsElevated = false;
	HANDLE hToken = NULL;

	DWORDLONG dwlConditionMask = 0;
	OSVERSIONINFOEX WinVersion;
	ZeroMemory(&WinVersion, sizeof(OSVERSIONINFOEX));
	WinVersion.dwOSVersionInfoSize = sizeof(OSVERSIONINFOEX);
	WinVersion.dwMajorVersion = 6;
	VER_SET_CONDITION(dwlConditionMask, VER_MAJORVERSION, VER_GREATER_EQUAL);

	BOOL flag = VerifyVersionInfo(
		&WinVersion,
		VER_MAJORVERSION,
		dwlConditionMask
	);

	if (!flag)//不是VISTA、Windows7
		return (false);

	do
	{
		HANDLE hProcess = NULL;
		if (bCurrentProcess)
		{
			hProcess = GetCurrentProcess();
		}
		else
		{
			hProcess = ::OpenProcess(PROCESS_QUERY_INFORMATION, FALSE, dwProcessId);
		}

		if (!hProcess)
		{
			bIsElevated = false;
			break;
		}

		HANDLE hToken = NULL;
		if (!::OpenProcessToken(hProcess, TOKEN_QUERY, &hToken))
		{
			bIsElevated = false;
			::CloseHandle(hProcess);
			break;
		}

		TOKEN_ELEVATION elevation;
		DWORD dwRetLen = 0;
		if (!::GetTokenInformation(hToken, TokenElevation, &elevation, sizeof(elevation), &dwRetLen))
		{
			bIsElevated = false;
			::CloseHandle(hToken);
			::CloseHandle(hProcess);
			break;
		}

		if (dwRetLen == sizeof(elevation))
		{
			bIsElevated = elevation.TokenIsElevated;
		}
		::CloseHandle(hToken);
		::CloseHandle(hProcess);

	} while (false);

	return bIsElevated;
}


 

转载请注明来源,谢谢。

有偿解决C++编程问题,承接项目定制开发;寻一份全职或兼职Windows C++开发工作。联系邮箱:[email protected]


老刀的技术日志 » C++:判断进程是否”以管理员身份运行”

发表评论