Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect when the Foreground windows changes

Tags:

winapi

I know which using the GetForegroundWindow function i can get the current active window handle, but now i want to detect when the active window (of any application) changes (become active). the first solution which come to my mind is

  1. store the current value (handle) returned by the GetForegroundWindow function.
  2. using a timer component check again the value returned by GetForegroundWindow and compare with the old value.

I'm wondering if exist a better way to do this maybe using a windows message or something else.

like image 710
Salvador Avatar asked May 03 '11 21:05

Salvador


1 Answers

Use SetWindowsHookEx to install a CBT hook. MSDN describes the callback function you'll provide:

The system calls this function before activating, creating, destroying, minimizing, maximizing, moving, or sizing a window; before completing a system command; before removing a mouse or keyboard event from the system message queue; before setting the keyboard focus; or before synchronizing with the system message queue. A computer-based training (CBT) application uses this hook procedure to receive useful notifications from the system.

The calls you'll be interested in are the ones where the first parameter is HCBT_Activate. The wParam parameter will tell you the window handle.

like image 86
Rob Kennedy Avatar answered Sep 28 '22 01:09

Rob Kennedy