-1

I have a simple cycle with simple window print function.

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

Problem is that it print only title of first active window. What i want to do is to print title of active window everytime it changes. Without if statement it works well(but still printing that active window).

  • 2
    `currbuf2` will usually never be equal to `currbuf` unless the compiler is merging duplicate string literals. However you set both of them to equal `temp`. That is not the way to compare a string in C. – Weather Vane Feb 19 '19 at 18:24
  • 2
    This will hog your CPU. – H H Feb 19 '19 at 18:24
  • @WeatherVane But if they never will be equal it will be printing something forever. But with that IF statement it prints only first active window. –  Feb 19 '19 at 18:26
  • @JurajJakubov I was editing the first comment. – Weather Vane Feb 19 '19 at 18:26
  • 1
    Thanks i was googling and going to try "strcmp". –  Feb 19 '19 at 18:28
  • 2
    You don't copy strings in C with `=` and even if you used `strcpy` the target is a (read-only) string literal of inadequate size. – Weather Vane Feb 19 '19 at 18:29
  • Possible duplicate of [How do I properly compare strings?](https://stackoverflow.com/questions/8004237/how-do-i-properly-compare-strings) – Govind Parmar Feb 19 '19 at 18:31

1 Answers1

2

Problem is that it print only title of first active window.

You need to compare the string contents, not the string pointers:

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

What i want to do is to print title of active window everytime it changes.

Rather than using an endless loop that constantly polls the active window, you should instead use SetWinEventHook() to receive EVENT_SYSTEM_FOREGROUND notifications from the OS whenever the foreground window changes. Don't poll (except maybe the first time before starting the hook).

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);
Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770