How to find whether a GUI application is freezed or is not responding?

25 04 2008

It’s common that windows citizens usually hang after long run. 😉 Sometimes your application was meant to run for long period but stop responding after days or months. So how to automatically restart it if it gets hang? One method is to schedule a polling application which checks the application periodically. But how to determine whether an application is hung?

You can send WM_NULL message to the application window by using the api – SendMessageTimeout(). The WM_NULL does nothing. It can be used for poll the window. If an appliaction window is hung, it may not be able to process the WM_NULL message. If we use SendMessage(), since its a blocking call out caller thread too will be blocked.

So we should use SendMessageTimeout() in which we can specify a timeout. In SendMessageTimeout() we can specify a flag – SMTO_ABORTIFHUNG which returns immedietly if the targeted application is hung. So SendMessageTimeout() is perfect for our purpouse. See the sample code snippet below.

DWORD Result = 0;
LRESULT Return = 0;

// Handle of application window.
// Get it by using FindWindowEx function.
// Here for compilation, i get the handle of my dialog.
HWND hWnd = GetSafeHwnd(); 

// Send the NULL message to the window.
// SMTO_ABORTIFHUNG is specified to return immediately,
// if the process is hung.
Return = ::SendMessageTimeout( hWnd, // Window Handle
                               WM_NULL, // Message
                               0,       // WParam
                               0,       // LParam
                               SMTO_ABORTIFHUNG, // Flags
                               500,              // Timeout
                               &Result );        // Result

// Check whether the WM_NULL message is processed.
if( !Return )
    // Since the WM_NULL message is not processed,
    // the targeted window is hung. Forget about it!

Customize it according to your wish.

Just like null checking the pointer, you can check, whether a window is perfect by sending WM_NULL message.

Targeted Audience – Intermediate.