Help with hooks

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.


1
2
3
4
5
6
7
8
9
10
11
12
void CALLBACK windowChangeHook(HWINEVENTHOOK hWinEventHook, DWORD event, HWND hwnd, LONG idObject, LONG idChild, DWORD dwEventThread, DWORD dwmsEventTime)
{
	MessageBoxA(NULL, "WINDOW CHANGE DETECT", "DETECT1", MB_OK);
}

int main()
{

HWINEVENTHOOK hEventHook = SetWinEventHook(EVENT_OBJECT_FOCUS, EVENT_OBJECT_FOCUS, NULL, &windowChangeHook, 0, 0, WINEVENT_OUTOFCONTEXT);


}	
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:
1
2
3
4
5
6
   MSG msg;
   while (GetMessage(&msg, NULL, 0, 0) != -1)
   {
    TranslateMessage(&msg);
    DispatchMessage(&msg);
   } 
Last edited on
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.


Have a look here maybe you find sth. useful:
https://www.codeproject.com/search.aspx?q=hooks+win+api&x=0&y=0&sbo=kw
Last edited on
Topic archived. No new replies allowed.