Create process without having keyboard and mouse, interaction and focus

566 views Asked by At

How to create/spawn Win32 process without mouse and keyboard focus and interaction?

Can some one mentioned most appropriate Win API function to create window process without having it display as top most window ,but stay behind in other opened windows?

(Assume you have to spawn/create a process of windowed(not fullscreen) Direct3D program executable and that program terminate by parent program therfore no need of user interaction but automated therefore when it gets created it should display behind other already opened windows).

1

There are 1 answers

0
Anders On

Starting a process with a inactive SW_* value is not enough but if you are the foreground window you can also call LockSetForegroundWindow to disable SetForegroundWindow:

void backgroundcalc_simple()
{
    LockSetForegroundWindow(LSFW_LOCK);
    ShellExecute(NULL, NULL, TEXT("Calc"), NULL, NULL, SW_SHOWNA);
    // Cannot unlock here without a hacky call to Sleep
}

If your application does not need SetForegroundWindow then you don't have to unlock but it is probably a good idea to do so anyway:

BOOL CALLBACK ProcessHasVisibleWindowProc(HWND hWnd, LPARAM Param)
{
    if (IsWindowVisible(hWnd) && (WS_CAPTION & GetWindowLongPtr(hWnd, GWL_STYLE)))
    {
        DWORD thispid, *wantedpid = (DWORD*) Param;
        if (GetWindowThreadProcessId(hWnd, &thispid) && thispid == *wantedpid)
        {
            *wantedpid = 0;
            return FALSE;
        }
    }
    return TRUE;
}
BOOL ProcessHasVisibleWindow(DWORD Pid)
{
    if (!Pid) return FALSE;
    EnumWindows(ProcessHasVisibleWindowProc, (LPARAM) &Pid);
    return Pid == 0;
}

BOOL WaitForVisibleProcessWindow(DWORD Pid, DWORD Timeout)
{
    DWORD start = GetTickCount();
    for (;;)
    {
        if (ProcessHasVisibleWindow(Pid)) return TRUE;
        if (GetTickCount() - start >= Timeout && Timeout != INFINITE) break;
        Sleep(50);
    }
    return FALSE;
}

void backgroundcalc()
{
    STARTUPINFO si;
    PROCESS_INFORMATION pi;
    ZeroMemory(&si, sizeof(si));
    si.cb = sizeof(si);
    si.dwFlags = STARTF_FORCEOFFFEEDBACK|STARTF_USESHOWWINDOW;
    si.wShowWindow = SW_SHOWNA;
    WCHAR cmd[MAX_PATH];
    lstrcpy(cmd, TEXT("Calc"));
    LockSetForegroundWindow(LSFW_LOCK);
    if (CreateProcess(NULL, cmd, NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi))
    {
        WaitForInputIdle(pi.hProcess, 3333);
        WaitForVisibleProcessWindow(pi.dwProcessId, 1000*10);
        CloseHandle(pi.hProcess);
        CloseHandle(pi.hThread);
    }
    LockSetForegroundWindow(LSFW_UNLOCK);
}