Playing a sound every time the foreground window changes

Raymond Chen

Today’s Little Program plays a little sound every time the foreground window changes. One of my colleagues wondered if such a program was possible, “so that I stop accidentally typing the second halves of paragraphs into windows that pop up and steal focus.” It’s not clear whether this program will actually solve the bigger problem, but it was fun writing the program, and maybe you can use it for something.

#define STRICT
#include <windows.h>
#include <mmsystem.h>
void CALLBACK WinEventProc(
    HWINEVENTHOOK hWinEventHook,
    DWORD event,
    HWND hwnd,
    LONG idObject,
    LONG idChild,
    DWORD dwEventThread,
    DWORD dwmsEventTime
  if (hwnd &&
      idObject == OBJID_WINDOW &&
      idChild == CHILDID_SELF &&
   PlaySound(TEXT("C:\\Windows\\Media\\Speech Misrecognition.wav"),
int WINAPI WinMain(HINSTANCE hinst, HINSTANCE hinstPrev,
                   LPSTR lpCmdLine, int nShowCmd)
  HWINEVENTHOOK hWinEventHook = SetWinEventHook(
     NULL, WinEventProc, 0, 0,
  MSG msg;
  while (GetMessage(&msg, NULL, 0, 0)) {
  if (hWinEventHook) UnhookWinEvent(hWinEventHook);
  return 0;

This program installs an accessibility hook that listens for changes to the system foreground. And when it happens, we play a little sound.

I chose the Windows 7 Speech Misrecognition sound because it’s relatively unobtrusive. And the sound is played asynchronously so as not to block the message pump thread. It also has as a pleasant side-effect that if the foreground changes many times rapidly, the new sound will interrupt the old one rather than queueing up behind it.

Note that there is no way to exit this program short of killing it in Task Manager. That’s why it’s a Little Program rather than a real program.


Comments are closed. Login to edit/delete your existing comments

Feedback usabilla icon