PDA

View Full Version : Intercept Ctrl-c from the command line



irudkin
21st August 2007, 15:10
Hi

I have a Qt GUI application which I can run from the Microsoft command line window. One of the options on the command line is for the application is to do some work (a batch job) and then quit. During the time the application is running I can stop the application by pressing ctrl-c in the command line window. The application will stop but not gracefully, it dies somewhere in Qt (qpaint something). How can I intercept Ctrl-c or hook into Qt/application shutting down so I can clean up properly?

I've looked at QSessionManager. I've tried using


if( QSysInfo::WindowsVersion >= QSysInfo::WV_XP )
{
// type of the pointer function to retrieve from the library
typedef BOOL (WINAPI* PFN_AttachConsole)(DWORD);

// get the module
HMODULE hModule= ::GetModuleHandleA( "kernel32.dll" );
// get the pointer to the function
PFN_AttachConsole fpAttachConsole = (BOOL (_stdcall *)(DWORD)) GetProcAddress( hModule, "AttachConsole" );

// check if the pointer is valid and retrieve the parent console
if( (NULL != fpAttachConsole) && (0 != fpAttachConsole( (DWORD)-1 )) )
{
// Process escape characters
SetConsoleMode( hModule, ENABLE_PROCESSED_OUTPUT | ENABLE_PROCESSED_INPUT );
m_hStdOut = GetStdHandle( STD_OUTPUT_HANDLE );
m_bSuccess = true;
}
}


I think a problem with the above it is not attached to a 'true' console and I so can't switch off ctrl-c (unless the above code is wrong?)

I have also tried windows functions



SetConsoleCtrlHandler( (PHANDLER_ROUTINE) gFnConsoleCtrlHandler, TRUE )

Using my function
BOOL gFnConsoleCtrlHandler( DWORD fdwCtrlType )
{
switch( fdwCtrlType )
{
// Handle the CTRL-C signal.
case CTRL_C_EVENT:
printf( "Ctrl-C event\n\n" );
//gFnApp_TidyUpOnExit(); Idea was to call something like this
return( TRUE );

// CTRL-CLOSE: confirm that the user wants to exit.
case CTRL_CLOSE_EVENT:
printf( "Ctrl-Close event\n\n" );
return( TRUE );

// Pass other signals to the next handler.
case CTRL_BREAK_EVENT:
printf( "Ctrl-Break event\n\n" );
return FALSE;

case CTRL_LOGOFF_EVENT:
printf( "Ctrl-Logoff event\n\n" );
return FALSE;

case CTRL_SHUTDOWN_EVENT:
printf( "Ctrl-Shutdown event\n\n" );
return FALSE;

default:
return FALSE;
}
}


but again this gets ignored :confused:

Ideally I would like to intercept the ctrl-c key, visit my tidy up function then let the app quit gracefull and keep Qt happy.

Any suggestions welcome :)

themolecule
21st August 2007, 22:05
in linux you use

#include <signal.h>

sighandler(int)
{
//do something here.
}

int main(int argc, char *argv[])
{
signal(SIGINT,sighandler);
}


there should be a windows equivalent