c++ 管理员启动程序

2021-07-13  本文已影响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;
}
上一篇下一篇

猜你喜欢

热点阅读