c++ - 替换 sleep 直到桌面上的窗口打开

标签 c++ windows winapi

当我打开一些软件应用程序时,我必须等待 2-3 秒,直到窗口显示在桌面上。我必须使用 Sleep(2000);然后调用方法 set always on top。我正在尝试在我的代码中替换 Sleep。我想从打开的窗口获取信号,然后调用一个方法,使打开的窗口始终位于最前面。 这是我的代码:

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;
}

最佳答案

可能最好的办法就是调用 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.

这是最接近等待进程显示其 UI 的一般方法。它不会总能满足您的要求,但它是目前最好的。

关于c++ - 替换 sleep 直到桌面上的窗口打开,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21480605/

相关文章:

c++ - 使用 <urlmon.h> 和 URLDownloadToFile 获取 HTTPS Web 资源

c++ - 如何找到文件/文件夹的所有硬链接(hard link)和符号链接(symbolic link)(Windows 和 UNIX)?

c++ - fatal error C1083 : Cannot open include file: 'mexutils.h' : No such file or directory

c++ - 为结构类调用构造函数

windows - 内存密集型应用程序的内存管理

ruby-on-rails - rails : How can I access my database on my host machine (windows) from a virtualbox guest (ubuntu)?

c++ - 我的二进制搜索有问题吗?

c++ - llvm::Type 结构的字符串表示

c++ - 在 DLL 中导出静态数据

c++ - 当用户调整对话框大小时,如何强制Windows不要在对话框中重绘任何内容?