首页 > 解决方案 > 循环未打印活动窗口

问题描述

我有一个带有简单窗口打印功能的简单循环。

char temp[100], *currbuf= "", *currbuf2 = "";


while (1) {
    GetWindowText(GetForegroundWindow(), temp, sizeof temp / sizeof *temp);
    currbuf2 = temp;
    if (currbuf2 != currbuf) {
        currbuf = temp;
        printf("\n\nWindow title: %s\n", temp);
    };
};

问题是它只打印第一个活动窗口的标题。我想要做的是在每次更改时打印活动窗口的标题。如果没有 if 语句,它运行良好(但仍然打印该活动窗口)。

标签: cwinapi

解决方案


问题是它只打印第一个活动窗口的标题。

您需要比较字符串内容,而不是字符串指针

char temp[100] = "", currbuf[100] = "";

while (1) {
    GetWindowText(GetForegroundWindow(), temp, sizeof temp / sizeof *temp);
    if (strcmp(currbuf, temp) != 0) {
        strcpy(currbuf, temp);
        printf("\n\nWindow title: %s\n", temp);
    }
}

我想要做的是在每次更改时打印活动窗口的标题。

与其使用不断轮询活动窗口的无限循环,不如使用在前台窗口更改时从操作系统SetWinEventHook()接收EVENT_SYSTEM_FOREGROUND通知。不要轮询(除了可能在开始钩子之前的第一次)。

void displayWindowTitle(HWND hWnd)
{
    char temp[100] = "";
    GetWindowText(hWnd, temp, sizeof temp / sizeof *temp);
    printf("\n\nWindow title: %s\n", temp);
}

void CALLBACK MyHookCallback(HWINEVENTHOOK hook, DWORD event, HWND hwnd, LONG idObject, LONG idChild, DWORD dwEventThread, DWORD dwmsEventTime)
{
    displayWindowTitle(hwnd);
}

...

displayWindowTitle(GetForegroundWindow());
HWINEVENTHOOK hHook = SetWinEventHook(EVENT_SYSTEM_FOREGROUND, EVENT_SYSTEM_FOREGROUND, NULL, &MyHookCallback, 0, 0, WINEVENT_OUTOFCONTEXT);
...
UnhookWinEvent(hHook);

推荐阅读