Hi guys, I'm very new to c++ and i recently came over problem of detecting active window change. I was using simple loop with while(1){} and GetForegroundWindow() but it's bad since it boost CPU usage to 60%. So after hitting some google, i found out that certain events can be hooked in order to detect change of active window. Now i'm not sure how is code under going to be triggered, should i combile SetWinEventHook with CreateThread or maybe some other way ? Please accept my excuses if question is stupid, I'm very new to this.
You could use <conditional_variable>, and basically wait for your callback to notify it so you can exit.
Also note you should Sleep(1) or std::this_thread::sleep_for( std::chrono::microseconds(1) ) inside any later spinlocks you make to be easy on the cpu, and you should also study microsoft docs throughly, since you don't have any comments in your code.
Thanks for your reply, I understand how to write hook but for me its unclear how to trigger it when event is called (in my case EVENT_OBJECT_FOCUS). As you can see I'm just trying to show simple messageBox on momment when active window is changed.
Does the function get called at all? Can you test with cout? Why are you using MessageBoxA instead of MessageBox? (I got mislead by not being through with figuring what it is, I was thinking it has some weird alert purpose).
Like Thomas1965 said, It turns out you need something like:
Why are you using MessageBoxA instead of MessageBox
It's a good idea since he uses const char*. If he would use MessageBox it would work only if the project uses Multibyte char set but break with a unicode charset.
Did you see this peace of doc at MSDN ?
The client thread that calls SetWinEventHook must have a message loop in order to receive events.