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