c++ 提升应用程序的权限


1、判断当前用户权限是否管理员权限

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;
}


2、 如果当前用户权限非管理员,提升当前用户权限

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;
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值