JBAS
JBAS

Reputation: 43

Replace Sleep until Window on desktop opened

When, I open some of the software applications I have to wait 2-3 seconds until window will show on desktop. I have to use Sleep(2000); and then call method set always on top. I'm trying to replace Sleep in my code. I would like to get signal from opened window and after this, call a method, which allows opened window be always on top. Here's my code:

BOOL CALLBACK EnumWindowsProc(HWND windowHandle, LPARAM lParam)
{

    DWORD searchedProcessId = (DWORD)lParam;
    DWORD windowProcessId = 0;
    GetWindowThreadProcessId(windowHandle, &windowProcessId);
    cout << "Process id: " << windowProcessId << endl;


    if(searchedProcessId == windowProcessId) {
        HWND hwnd = windowHandle;

        Sleep(2000);                    
        SetWindowPos(hwnd, HWND_TOPMOST, 0, 0, 0, 0, SWP_NOMOVE|SWP_NOSIZE);
        cout << "Process ID found!" << endl;

        return TRUE;
    }
    return TRUE;
}

void AlwaysOnTop(int processId)
{
        EnumWindows(&EnumWindowsProc, (LPARAM)processId);   
}


void AlwaysOnTop(char *name)
{

        cout << "String: " << name << endl;

        Sleep(2000);
        HWND h = FindWindow(NULL, (LPCSTR) name);
        SetActiveWindow(h); 
        SetForegroundWindow(h);
        SetWindowPos(h, HWND_TOPMOST, 0,0,0,0, SWP_NOSIZE | SWP_NOMOVE);

}



int main()
{

    char s[] = {"Application"};

    AlwaysOnTop(s);
    //AlwaysOnTop(2307);

    system("PAUSE");
    return 0;
}

Upvotes: 1

Views: 153

Answers (1)

David Heffernan
David Heffernan

Reputation: 613432

Probably the best you can do is to call WaitForInputIdle:

Waits until the specified process has finished processing its initial input and is waiting for user input with no input pending, or until the time-out interval has elapsed.

This is the closest you can get to a general way to wait until a process is showing its UI. It won't always do what you want, but it's the best there is.

Upvotes: 2

Related Questions