清泛IT社区
标题:
c++ 代码提升权限,请求管理员身份运行权限
[打印本页]
作者:
清泛网
时间:
2016-04-08 17:12
标题:
c++ 代码提升权限,请求管理员身份运行权限
普通的启动一个程序使用
CreateProcess
函数,有时会遇到权限不足失败的情况,那么如何提升执行权限呢?
使用
ShellExecuteEx
函数:
// ------提升权限------
// Initialize the structure.
SHELLEXECUTEINFO sei = { sizeof(SHELLEXECUTEINFO) };
sei.fMask = SEE_MASK_NOCLOSEPROCESS;
// Ask for privileges elevation.
sei.lpVerb = TEXT("runas");
// Create a Command Prompt from which you will be able to start
// other elevated applications.
sei.lpFile = szFile;
sei.lpParameters = szCmdline;
sei.lpDirectory = szWorking;
// Don't forget this parameter; otherwise, the window will be hidden.
sei.nShow = SW_SHOWNORMAL;
if (!ShellExecuteEx(&sei)) {
DWORD dwStatus = GetLastError();
if (dwStatus == ERROR_CANCELLED) {
// The user refused to allow privileges elevation.
UpdateMessage(_T("用户拒绝安装,升级失败。"));
}
else if (dwStatus == ERROR_FILE_NOT_FOUND) {
// The file defined by lpFile was not found and
// an error message popped up.
UpdateMessage(_T("升级包不存在,请检查!"));
}
CString strMsg;
::GetLastErrorString(strMsg);
LOG_ERROR(_T("启动安装程序失败:%s"), strMsg);
return -1;
}
m_hCreatePackage = sei.hProcess; // 句柄
复制代码
m_hCreatePackage 存储已启动进程的句柄,有了它我们就可以使用
WaitForSingleObject 对
其执行各阶段的逻辑进行处理了。
欢迎光临 清泛IT社区 (https://bbs.tsingfun.com/)
Powered by Discuz! X3.3