Method to allow abort of long processes

This is a simple way to abort from a long computation if the escape key is
pressed. Just call escape_pressed() periodically from your procedure, and if
TRUE is returned, abort.


BOOL escape_pressed() // return TRUE if escape pressed
{
 MSG msg;
 // check for messages and remove from queue
 if (::PeekMessage(&msg, NULL, 0, 0, PM_REMOVE) && msg.message == WM_KEYDOWN)
 {
  if (VK_ESCAPE == msg.wParam) // escape pressed
   return TRUE;
 }
 return FALSE;
}

One issue is that calling escape_pressed causes the wait cursor to go away.
To resolve this, just call Restore as follows:


CWaitCursor hg; //  show wait cursor

…from inside a loop doing a lengthy computation


if (escape_pressed() )
{
 break;
}
else
{
 // restore wait cursor. escape_pressed() causes wait
 // cursor to go away
 hg.Restore();
}

More by Author

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Must Read