How To Determine If A Window Is Active (In C)

As promised in my previous blog describing how to add activity notification flash to PuTTY here is another way to check if the window is active. Instead of keeping track of the current window state by handling the WM_ACTIVATE message you can directly query a window for its status with GetWindowInfo(). The WINDOWINFO.dwWindowStatus field will be set to WS_ACTIVECAPTION when the window is active.

Paste the following snippet at the end of window.c:

/* MARK SLETTERINK - ACTIVITY NOTIFICATION SUPPORT - WINDOW ACTIVE DETECTION2 */
/* SNIPPET ID: {CE84000D-9024-45f1-B0E6-5029AD1B257F} */
BOOL is_window_active()
{
   BOOL bActive=FALSE;
   BOOL bResult;
   WINDOWINFO wi;
 
   memset(&wi, 0, sizeof(wi));
   wi.cbSize=sizeof(wi);
 
   bResult=GetWindowInfo(hwnd, &wi);
 
   if(bResult)
      bActive = (wi.dwWindowStatus==WS_ACTIVECAPTION);
 
   return bActive;
}
/* MARK SLETTERINK - END OF ACTIVITY NOTIFICATION SUPPORT - WINDOW ACTIVE DETECTION2 */

Then add a forward declaration to the forward declarations (Snippet ID: D8B4F4A3-F870-4ded-B298-EEB71701D25D), it will look like this:

/* MARK SLETTERINK - ACTIVITY NOTIFICATION SUPPORT - FLASH METHODS FORWARD DECLARATIONS AND VARS */
/* SNIPPET ID: {D8B4F4A3-F870-4ded-B298-EEB71701D25D}-20090922*/
static void flash_window_activity(int mode);
static BOOL window_is_active=TRUE;
static BOOL activity_blink_done=FALSE;
BOOL is_window_active();
/* MARK SLETTERINK - END OF ACTIVITY NOTIFICATION SUPPORT - FLASH METHODS FORWARD DECLARATIONS AND VARS*/

 

With this new code in place all that is left is updating the activity detection logic to use it. This is implemented in the from_backend method, replace the use of the window_is_active boolean with the new is_window_active() method call so the code will look like this:

int from_backend(void *frontend, int is_stderr, const char *data, int len)
{
/* MARK SLETTERINK - ACTIVITY NOTIFICATION SUPPORT - SESSION ACTIVITY DETECTION */
/* SNIPPET ID: {9198643F-09DF-466f-971F-EB05EA15A85E}-20090922 */
   if(!is_window_active())
      flash_window_activity(2);
/* MARK SLETTERINK - END OF ACTIVITY NOTIFICATION SUPPORT - SESSION ACTIVITY DETECTION */
   return term_data(term, is_stderr, data, len);
}

 

All that is left now is compiling the code and firing up PuTTY!

Enjoy!

My Latest Track