需要时提升权限

经Win7、VS2013Update3环境下测试可用

调用示例

					std::wstring modulePath;
					kagula::CDirAndFile::GetExeFilePath(modulePath);
					CString dstDir = modulePath.c_str();
					if (IsAppRunningAsAdminMode() == TRUE || IsInProgramFiles(dstDir) == FALSE)
					{
						//... ...
					}
					else
					{
						//kagula::KagulaUtility::MsgBox(L"发现更新包!", L"为了更新软件,请提升应用程序的权限,按确定继续!");
						wchar_t szPath[MAX_PATH];
						if (GetModuleFileName(NULL, szPath, ARRAYSIZE(szPath)))
						{
							// Launch itself as admin
							//http://www.codeproject.com/Articles/320748/Haephrati-Elevating-during-runtime
							SHELLEXECUTEINFO sei = { sizeof(sei) };
							sei.lpVerb = L"runas";
							sei.lpFile = szPath;
							sei.hwnd = NULL;
							sei.nShow = SW_NORMAL;
							ShellExecuteEx(&sei);
						}


引用的代码段

BOOL IsInProgramFiles(CString cstrPath)
{
	TCHAR szPath[MAX_PATH] = { 0 };
	SHGetFolderPath(NULL, CSIDL_PROGRAM_FILES, NULL, SHGFP_TYPE_CURRENT, szPath);
	if (cstrPath.Find(szPath) >= 0)
	{
		{
			CString msg;
			msg.Format(L"[%s]路径在CSIDL_PROGRAM_FILES里,如果需要往这个路径写文件,需要用户提升权限!",cstrPath.GetBuffer());
			LOG_TRACE(msg.GetBuffer());
		}
		return TRUE;
	}
	return FALSE;
}

BOOL IsAppRunningAsAdminMode()
{
	BOOL fIsRunAsAdmin = FALSE;
	DWORD dwError = ERROR_SUCCESS;
	PSID pAdministratorsGroup = NULL;

	// Allocate and initialize a SID of the administrators group.
	SID_IDENTIFIER_AUTHORITY NtAuthority = SECURITY_NT_AUTHORITY;
	if (!AllocateAndInitializeSid(
		&NtAuthority,
		2,
		SECURITY_BUILTIN_DOMAIN_RID,
		DOMAIN_ALIAS_RID_ADMINS,
		0, 0, 0, 0, 0, 0,
		&pAdministratorsGroup))
	{
		dwError = GetLastError();
		goto Cleanup;
	}

	// Determine whether the SID of administrators group is enabled in 
	// the primary access token of the process.
	if (!CheckTokenMembership(NULL, pAdministratorsGroup, &fIsRunAsAdmin))
	{
		dwError = GetLastError();
		goto Cleanup;
	}

Cleanup:
	// Centralized cleanup for all allocated resources.
	if (pAdministratorsGroup)
	{
		FreeSid(pAdministratorsGroup);
		pAdministratorsGroup = NULL;
	}

	// Throw the error if something failed in the function.
	if (ERROR_SUCCESS != dwError)
	{
		throw dwError;
	}

	return fIsRunAsAdmin;
}
如果想一直使用Admin权限可以参考下面的资料设置项目属性。

《C++: Run program as administrator》

http://stackoverflow.com/questions/19617955/c-run-program-as-administrator


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值