I'm trying to listen to events in a third-party app window, in which I don't own the source.
I don't understand this part of the 
CodePudding user response:
The message loop needs to be in main, in your case after the call to SetWinEventHook. And since you don't otherwise have a way for your program to exit you'll probably want to create a dialog with an exit button, and in the handler for that buttons BN_CLICKED use a call to MessageBox to confirm that the user wants to exit and if so do a PostQuitMessage). The confirmation is because it would be too easy to exit otherwise.
CodePudding user response:
The message loop you have shown is perfectly fine (after moving it into EventHook()).
The "crash" is not really a crash. It is simply the program terminating itself abruptly because the thread is still running when the std::thread object is destroyed, as you have not called join() or detach() on it before it went out of scope when _tmain() exited.
Per std::thread::~thread:
Destroys the thread object.
If
*thishas an associated thread (joinable() == true),std::terminate()is called.Notes
A thread object does not have an associated thread (and is safe to destroy) after
So, simpy call t1.join() before _tmain() exits:
int _tmain(int argc, _TCHAR* argv[])
{
std::thread t1(EventHook);
...
t1.join();
return 0;
}
