普通的启动一个程序使用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 对其执行各阶段的逻辑进行处理了。
完整代码请参考Github:LiveUpdateDlg.cpp