Intercepting the X button

Discussion of chess software programming and technical issues.

Moderators: hgm, Dann Corbit, Harvey Williamson

User avatar
Rebel
Posts: 6946
Joined: Thu Aug 18, 2011 12:04 pm

Intercepting the X button

Post by Rebel »

I have been browsing the Internet for C-code (or technique) that when a user closes a Windows console application via the X button intercepts the signal and moves to a predefined routine such as you can do intercepting CTRL_C and CTRL_BREAK.

In the meantime I wonder if that is possible at all.
User avatar
rvida
Posts: 481
Joined: Thu Apr 16, 2009 12:00 pm
Location: Slovakia, EU

Re: Intercepting the X button

Post by rvida »

Rebel wrote:I have been browsing the Internet for C-code (or technique) that when a user closes a Windows console application via the X button intercepts the signal and moves to a predefined routine such as you can do intercepting CTRL_C and CTRL_BREAK.

In the meantime I wonder if that is possible at all.
Use SetConsoleCtrlHanlder() API to install the handler:

Code: Select all

if (SetConsoleCtrlHandler(
    (PHANDLER_ROUTINE)ConsoleHandler,TRUE)==FALSE)
{
    printf("Unable to install handler!\n");
    return -1;
}
When the user presses the X button your handler will be invoked with CTRL_CLOSE_EVENT parameter. Note that there is a 5 second timeout in which it must return before the app will be forcibly terminated.

Code: Select all

BOOL WINAPI ConsoleHandler(DWORD CEvent)
{
    switch(CEvent)
    {
    case CTRL_C_EVENT:
        MessageBox(NULL,
            "CTRL+C received!","CEvent",MB_OK);
        break;
    case CTRL_BREAK_EVENT:
        MessageBox(NULL,
            "CTRL+BREAK received!","CEvent",MB_OK);
        break;
    case CTRL_CLOSE_EVENT:
        MessageBox(NULL,
            "Program being closed!","CEvent",MB_OK);
        break;
    case CTRL_LOGOFF_EVENT:
        MessageBox(NULL,
            "User is logging off!","CEvent",MB_OK);
        break;
    case CTRL_SHUTDOWN_EVENT:
        MessageBox(NULL,
            "User is logging off!","CEvent",MB_OK);
        break;

    }
    return TRUE;
}
User avatar
Rebel
Posts: 6946
Joined: Thu Aug 18, 2011 12:04 pm

Re: Intercepting the X button

Post by Rebel »

This is cool. Thank you.