C++窗口扫描仪

C++ Window Scanner

本文关键字:扫描仪 窗口 C++      更新时间:2023-10-16

需要有关循环的帮助。我的想法是扫描窗口,当一个窗口找到时,检查它的进程Id,这样如果已经找到了窗口,就不要再试图找到它。我的代码中有一段是这样的:

if (Selection == 1)
{
    cout << endl << "================================= Scan Result =================================" << endl;
    cout << endl << "Scan Log:                                                        Times Found: " << TimesFound << endl;
    cout << "   - Scanning windows..." << endl;
    while(PressedKey != 27)
    {
        if (kbhit())
        {
            PressedKey = getch();
        }
        HWND WindowFound = FindWindow(0, "Untitled - Notepad");
        if (WindowFound != 0) 
        {
                            // My Idea was compare the procces Id of the found window
                            // to learn the found window was already found
            DWORD ProcessId;
            GetWindowThreadProcessId(WindowFound, &ProcessId);
            if(ProcessId != OtherId)
            {
                TimesFound++;
                cout << "Window found ! Times found: " << TimesFound << endl;
            }
        }
    }
}

我希望你们能帮助我。为干杯

编辑:新代码

BOOL CALLBACK EnumFunc(HWND hwnd, LPARAM lParam)
{
    wchar_t lpString[32];
    GetWindowText(hwnd, (LPSTR)lpString, _countof(lpString));
    if(wcscmp(lpString, L"Untitled - Notepad") == 0) 
    {
        *((int *)lParam)++;
    }
    return TRUE;
}

*((int*)lParam)++的这一部分;代码不起作用。错误是:表达式必须是可修改的左值@MikeKwan

编辑:我又有同样的问题@MikeKwan:)

    while(PressedKey != 27)
    {
        if (kbhit())
        {
            PressedKey = getch();
            printf("Times found: %d n", TimesFound);
        }
        EnumWindows(EnumFunc, (LPARAM)&TimesFound);
    }

我每次都用这个代码来检测窗口,但它检测一个窗口,并一次又一次地重新检测同一个窗口。所以什么都没有改变:/

在您的情况下,FindWindow不知道您已经看到的窗口列表,因此它将继续返回相同的窗口(尽管这是实现定义的)。无论如何,FindWindow都无法执行您正在尝试的操作(在搜索过程中跳过窗口)。

如果只想枚举所有窗口一次,则应使用EnumWindows。我为EnumWindows编写了一些示例C代码,我猜它实现了您想要实现的目标。您需要将其转换为C++,但您对C++的使用目前并不特别适合该语言。

BOOL CALLBACK EnumFunc(HWND hwnd, LPARAM lParam)
{
    /*
     * We don't care about getting the whole string,
     * just enough to do the comparison. GetWindowText
     * will truncate the string if we tell it to.
     */
    wchar_t lpString[32];
    GetWindowText(hwnd, lpString, _countof);
    if(wcscmp(lpString, L"Untitled - Notepad") == 0) {
        (*(int *)param)++;
    }
    return TRUE;
}
int main(void)
{
    int numFound = 0;
    EnumWindows(EnumFunc, (LPARAM)&numFound);
    return ERROR_SUCCESS;
}

(只是在回答窗口中写了这个,所以可能会有小错误)。