June 1st, 2018

How can I write a program that monitors another window for a title change?

A customer was writing a monitoring application and wanted to be notified if a window’s title changes.

Sure, we can use accessibility to do that.

#define UNICODE
#define _UNICODE
#define STRICT
#include <windows.h>
#include <stdio.h>

HWND g_hwndMonitor;

void CALLBACK WinEventProc(
  HWINEVENTHOOK hook,
  DWORD event,
  HWND hwnd,
  LONG idObject,
  LONG idChild,
  DWORD idEventThread,
  DWORD time)
{
  if (hwnd == g_hwndMonitor &&
      idObject == OBJID_WINDOW &&
      idChild == CHILDID_SELF &&
      event == EVENT_OBJECT_NAMECHANGE) {
      printf("title changed\n");
  }
}

int __cdecl main(int, char**)
{
 g_hwndMonitor = FindWindow(L"Awesome Program", nullptr);
 DWORD processId;
 DWORD threadId = GetWindowThreadProcessId(g_hwndMonitor, &processId);
 HWINEVENTHOOK hook = SetWinEventHook(
    EVENT_OBJECT_NAMECHANGE,
    EVENT_OBJECT_NAMECHANGE,
    nullptr,
    WinEventProc,
    processId,
    threadId,
    WINEVENT_OUTOFCONTEXT);
 MessageBox(nullptr, L"Press OK when bored", L"Title", MB_OK);

 UnhookWinEvent(hook);
 return 0;
}

The program starts by identifying the window it wants to monitor. Presumably the customer will use some domain-specific knowledge to find the window, but here, we’ll just demonstrate with the FindWindow function.

We get the thread and process ID for the window and use it to register a thread-specific accessibility event hook, filtered to name changes.

In the event callback, we see if the notification is for the window we are monitoring. If so, we print a message. The customer’s program would presumably do something more interesting than just print a message.

Topics
Code

Author

Raymond has been involved in the evolution of Windows for more than 30 years. In 2003, he began a Web site known as The Old New Thing which has grown in popularity far beyond his wildest imagination, a development which still gives him the heebie-jeebies. The Web site spawned a book, coincidentally also titled The Old New Thing (Addison Wesley 2007). He occasionally appears on the Windows Dev Docs Twitter account to tell stories which convey no useful information.

0 comments

Discussion are closed.