Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use SetWinEventHook() function to get Active Window changed message

Tags:

c++

window

winapi

I have been working on a project which needs to detect current active window and get the active window title continuously. Can anyone explain me how to use SetWinEventHook() function to get Active Window changed message. [ i used GetForegroundWindow() function with a timer to get the active window. That approach is not very accurate because of the timer. So i need to use it with SetWinEventHook() function. can someone explain me how to do that? ]

hEvent = SetWinEventHook(EVENT_SYSTEM_FOREGROUND , EVENT_SYSTEM_FOREGROUND ,NULL, 
WinEventProcCallback, 0, 0, WINEVENT_OUTOFCONTEXT | WINEVENT_SKIPOWNPROCESS);


VOID CALLBACK WinEventProcCallback ( HWINEVENTHOOK hWinEventHook, DWORD dwEvent, HWND hwnd, LONG idObject, LONG idChild, DWORD dwEventThread, DWORD dwmsEventTime)
{
      /* how to get active window message */
}
like image 271
Deadlock Avatar asked Jun 23 '15 09:06

Deadlock


1 Answers

I have found the solution. EVENT_SYSTEM_FOREGROUND Event is the missing piece. The system sends this event even if the foreground window has changed to another window. We can use this event to get the current active window.

VOID CALLBACK WinEventProcCallback ( HWINEVENTHOOK hWinEventHook, DWORD dwEvent, HWND hwnd, LONG idObject, LONG idChild, DWORD dwEventThread, DWORD dwmsEventTime)
{
     if (dwEvent == EVENT_SYSTEM_FOREGROUND)
     {
         /* do something */
     }
}
like image 126
Deadlock Avatar answered Nov 15 '22 00:11

Deadlock