美文网首页
c++ 管理员启动程序

c++ 管理员启动程序

作者: 海天启航 | 来源:发表于2021-07-13 14:51 被阅读0次
    static int RestartAsAdmin(LPCWSTR lpCmdLine, LPCWSTR cwd)
    {
        wchar_t myPath[MAX_PATH];
        if (!GetModuleFileNameW(nullptr, myPath, _countof(myPath) - 1)) {
            return 0;
        }
    
        SHELLEXECUTEINFO shExInfo = {0};
        shExInfo.cbSize = sizeof(shExInfo);
        shExInfo.fMask = SEE_MASK_NOCLOSEPROCESS;
        shExInfo.hwnd = 0;
        shExInfo.lpVerb = L"runas";        /* Operation to perform */
        shExInfo.lpFile = myPath;          /* Application to start */
        shExInfo.lpParameters = lpCmdLine; /* Additional parameters */
        shExInfo.lpDirectory = cwd;
        shExInfo.nShow = SW_NORMAL;
        shExInfo.hInstApp = 0;
    
        /* annoyingly the actual elevated updater will disappear behind other
         * windows :( */
        AllowSetForegroundWindow(ASFW_ANY);
    
        /* if the admin is a different user, save the path to the user's
         * appdata so we can load the correct manifest */
        CoTaskMemPtr<wchar_t> pOut;
        HRESULT hr = SHGetKnownFolderPath(FOLDERID_RoamingAppData,
                          KF_FLAG_DEFAULT, nullptr, &pOut);
        if (hr == S_OK)
            SetEnvironmentVariable(L"OBS_USER_APPDATA_PATH", pOut);
    
        if (ShellExecuteEx(&shExInfo)) {
            DWORD exitCode;
    
            WaitForSingleObject(shExInfo.hProcess, INFINITE);
    
            if (GetExitCodeProcess(shExInfo.hProcess, &exitCode)) {
                if (exitCode == 1) {
                    return exitCode;
                }
            }
            CloseHandle(shExInfo.hProcess);
        }
        return 0;
    }
    

    相关文章

      网友评论

          本文标题:c++ 管理员启动程序

          本文链接:https://www.haomeiwen.com/subject/dscspltx.html