I have an application that I want to run in the background with no visible windows or consoles. To accomplish this, I create a windows application but I do not create a window.
Do not bother with creating a dummy window, there is a much easier way to handle shutdown / exit control events in a windowless application. To do this, you use a little known Win API function called: SetConsoleCtrlHandler (...)
Here is an example of how to use the Control Handler:
#include
// You can fill-in your own behavior, this is just an example handler that
// covers most of the most common events.
BOOL
ControlHandler (DWORD dwControlEvent)
{
switch (dwControlEvent)
{
// User wants to shutdown
case CTRL_SHUTDOWN_EVENT:
return FALSE;
// User wants to logoff
case CTRL_LOGOFF_EVENT:
return FALSE;
// Ctrl + C
case CTRL_C_EVENT:
return TRUE;
// User wants to exit the "normal" way
case CTRL_CLOSE_EVENT:
return TRUE;
// Everything else, just ignore it...
default:
return FALSE;
}
}
int
main (void)
{
// Set the control handler so the app will be notified upon any special
// termination event.
SetConsoleCtrlHandler ((PHANDLER_ROUTINE) ControlHandler, TRUE);
//
// Main Loop Here ...
//
return 0;
}
I had to learn about this a couple of years ago because some middle-ware was not properly cleaning up its resources when my console application was terminated with Ctrl + C. I discovered it by accident when I was looking at the stack trace. It is worth mentioning that this supercedes the standard signal handler for events like Ctrl + C.
By the way, even though it is called a "Console Control Handler," it works perfectly fine in applications that use WinMain (...)
instead of main (...)
.