C++: Detect when Windows Explorer has crashed

Despite excellent progress from the days of Windows 95, Windows Explorer is still prone to the random crashes here and there; may it be out of spite after years of user stupidity, hardware problems, rogue software installed, hacked system files which compromise stability or just a random act of cruelty from a supernatural force.

imageAs a developer, it's our duty to keep our programs working as well as possible. Little things which keep our program accessible after an Explorer crash such as restoring the taskbar icon will make users happy.

Fortunately, it's easy enough to detect when Explorer crashes. I guess Microsoft got used to problems within 3rd party software not doing stuff right and implemented an event for it.

In your header file, define a message called WM_TASKBARCREATED.

UINT WM_TASKBARCREATED = 0;

In your InitInstance() call, after the handle is created:

// Set up a message to detect when Explorer has crashed
WM_TASKBARCREATED = RegisterWindowMessage(TEXT("TaskbarCreated"));

This will register a message for the duration of your program. It will automatically be discarded when the program ends.

Finally, add a handler for the message in WndProc():

switch (message) {
case WM_COMMAND:
...
break;

case WM_DESTROY:
...
break;

default:
// If Explorer has crashed/restarted, re-initialise the program
if (message == WM_TASKBARCREATED) {
// Put your crash handler code here, or make a function and call it from here
}
break;
}

The reason we put it into the default is that switch blocks need hardcoded values to work, but our WM_TASKBARCREATED message value is assigned everytime the program is run.

Note that tray icons for Windows features (such as network icons, sound, etc) have a brief delay of about 3-5 seconds before restoring themselves.

I would also advise to follow that practice and use a timer to handle the crash-restore code. Restoring something immediately before Explorer has fully initialised may cause it to freeze up, leaving your system in an unusable state.

Sources

 
Copyright © Twig's Tech Tips
Theme by BloggerThemes & TopWPThemes Sponsored by iBlogtoBlog