サービスで管理者権限でプロセスを作成する


HANDLE hToken;
    HDESK hdesk;
    HWINSTA hwinsta;
    PROCESS_INFORMATION pi;
    PSID psid;
    STARTUPINFO si;

    //
    // obtain an access token for the user fester
    //
    if (!LogonUser(
        strUser, // “administrator"
        NULL,
        strPwd,  // “password”
        LOGON32_LOGON_INTERACTIVE,
        LOGON32_PROVIDER_DEFAULT,
        &hToken))
    {
        goto end;
    }
    //
    // obtain a handle to the interactive windowstation
    //
    hwinsta = OpenWindowStation(
        "winsta0",
        FALSE,
        READ_CONTROL | WRITE_DAC
        );
    if (hwinsta == NULL)
        goto end;

    HWINSTA hwinstaold = GetProcessWindowStation();

    //
    // set the windowstation to winsta0 so that you obtain the
    // correct default desktop
    //
    if (!SetProcessWindowStation(hwinsta))
        goto end;

    //
    // obtain a handle to the "default" desktop
    //
    hdesk = OpenDesktop(
        "default",
        0,
        FALSE,
        READ_CONTROL | WRITE_DAC |
        DESKTOP_WRITEOBJECTS | DESKTOP_READOBJECTS
        );
    if (hdesk == NULL)
        goto end;
    //
    // obtain the logon sid of the user fester
    //
    if (!ObtainSid(hToken, &psid))
        goto end;

    //
    // add the user to interactive windowstation
    //
    if (!AddTheAceWindowStation(hwinsta, psid))
        goto end;

    //
    // add user to "default" desktop
    //
    if (!AddTheAceDesktop(hdesk, psid))
        goto end;

    //
    // free the buffer for the logon sid
    //
    RemoveSid(&psid);

    //
    // close the handles to the interactive windowstation and desktop
    //
    CloseWindowStation(hwinsta);

    CloseDesktop(hdesk);

    //
    // initialize STARTUPINFO structure
    //
    ZeroMemory(&si, sizeof(STARTUPINFO));
    si.cb = sizeof(STARTUPINFO);
    si.lpDesktop = "winsta0\\default";


    //
    // start the process
    //
    if (!CreateProcessAsUser(
        hToken,
        NULL,
        (LPSTR)(LPCTSTR)strcmd,
        NULL,
        NULL,
        FALSE,
        NORMAL_PRIORITY_CLASS | CREATE_NEW_CONSOLE,
        //CREATE_NO_WINDOW|NORMAL_PRIORITY_CLASS,
        NULL,
        NULL,
        &si,
        &pi
        ))
    {
        goto end;
    }

    SetProcessWindowStation(hwinstaold); //set it back

    //
    // close the handles
    //
    CloseHandle(pi.hProcess);

    CloseHandle(pi.hThread);