I'm interested in the window title of the currently focused window. I now have this code which basically works:
#include <iostream>
#include <Windows.h>
using namespace std;
void CALLBACK myCallback(HWINEVENTHOOK hWinEventHook,
DWORD event,
HWND hwnd,
LONG idObject,
LONG idChild,
DWORD idEventThread,
DWORD dwmsEventTime) {
int windowTitleLength = GetWindowTextLengthA(hwnd);
const int bufferSize = windowTitleLength + 2;
LPSTR windowTitleBuffer = new char[bufferSize];
GetWindowTextA(hwnd, windowTitleBuffer, bufferSize);
cout << "Title: " << windowTitleBuffer << endl;
delete[] windowTitleBuffer;
}
void setup() {
SetWinEventHook(EVENT_SYSTEM_FOREGROUND, EVENT_SYSTEM_FOREGROUND, NULL, myCallback, 0, 0,
WINEVENT_OUTOFCONTEXT | WINEVENT_SKIPOWNPROCESS);
}
int main()
{
bool bRet;
MSG myMsg;
setup();
while (bRet = GetMessage(&myMsg, NULL, 0, 0) != 0)
{
if (bRet == -1) {
cout << "ABANDON SHIP!" << endl;
}
cout << "Got a message!" << endl;
}
}
And btw this is my attempt to achieve in c++ what I failed to achieve in nodejs here.
The window titles get printed as expected until I explicitly focus the terminal window of my little program. It prints it's own title then freezes. Focusing other windows does not print anything until I press Ctrl+C in my console then all the stored energy in my program's memory is released and starts working again.
Now I don't know why the callback is being called for my own program console window when I have specified WINEVENT_SKIPOWNPROCESS
flag to SetWinEventHook
. Maybe because the console is not really a window?
The second question I have about this code is the GetMessage
function which gets called only once no matter how many events my program receives which doesn't make sense to me because I expect it to be called once for each event received.
Also, maybe as a consequence to the above, the while
loop body never executes.
How to get this program to not choke on it's own events?