c++ 提升应用程序的权限
判断当前用户权限是否管理员权限 BOOL IsRunAsAdmin() { 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; } 如果当前用户权限非管理员,提升当前用户权限 BOOL ElevateCurrentProcess(CString sCmdLine) { USES_CONVERSION; TCHAR szPath[MAX_PATH] = {0}; if (::GetModuleFileName(NULL, szPath, MAX_PATH)){ // Launch itself as administrator. SHELLEXECUTEINFO sei = { sizeof(SHELLEXECUTEINFO) }; sei.lpVerb = _T("runas"); sei.lpFile = szPath; sei.lpParameters = (LPCTSTR)sCmdLine; // sei.hwnd = hWnd; sei.nShow = SW_SHOWNORMAL; if (!ShellExecuteEx(&sei)){ DWORD dwStatus = GetLastError(); if (dwStatus == ERROR_CANCELLED) { return FALSE; }else if (dwStatus == ERROR_FILE_NOT_FOUND) { return FALSE; } return FALSE; } return TRUE; } return FALSE; }查看完整版本: c++ 提升应用程序的权限
Tags: