经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