console exit event / file save

i have a list class that i need to save upon exit i cant figure out a way to do this using this method can make this method a mwmber of the class or pass the object with it?

BOOL WINAPI ConsoleHandler(DWORD CEvent)
{

ofstream o;

if(CEvent==CTRL_C_EVENT|| CTRL_BREAK_EVENT|| CTRL_CLOSE_EVENT|| CTRL_LOGOFF_EVENT||
CTRL_SHUTDOWN_EVENT)
{
cout<<"program exit detected ";


//

}
return 1;
}

void main()
{
if (SetConsoleCtrlHandler( (PHANDLER_ROUTINE)ConsoleHandler,TRUE)==FALSE)
{
// unable to install handler...
// display message to the user
printf("Unable to install handler!\n")

//save file;
}


}
Why do you need a console control handler? Can't you do it in the destructor of a class? Sounds simpler to me.

1
2
3
4
5
6
7
8
9
10
11
12
13
class GoOnExit
{
    ~GoOnExit()
    {
        //Put your code here.
    }
}

int main()
{
    GoOnExit __willDoOnExit;
    //Now no matter how the program exits, the destructor of __willDoOnExit will execute.
}
Something like this?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
BOOL WINAPI ConsoleHandler(DWORD dwCtrlEvent)
{
    switch (dwCtrlEvent)
    {
    case CTRL_C_EVENT:
    case CTRL_BREAK_EVENT:
    case CTRL_CLOSE_EVENT:
    case CTRL_LOGOFF_EVENT:
        {
            std::ofstream os("appstate.save");
            os << gAppState << std::endl;  // Assume the state's in global gAppState
            return TRUE;
        }

    case CTRL_SHUTDOWN_EVENT:
    default:
        return FALSE;
    }
}
the dtor doest hit on x click and rhe handler would need to some how take a typer arg or be a class member neither seem to work
my question is how to access the list class from inside the ctrlhandler or enter back into the main function to perform the save
Topic archived. No new replies allowed.