2

Is there a way to call a function at termination(clicking on the red X of the console) of an non-Object-oriented console application(simple main program)?

Maybe to catch the message of the red X and handle it then...

Thanks!

  • _Clicking on the X of the console_ doesn't mean exit necessarily. Please be specific on what you've done, what's the problem you're facing, instead of being vague. – legends2k Jan 28 '14 at 11:25
  • Why don't you describe your problem instead of the solution you have in mind... – StoryTeller - Unslander Monica Jan 28 '14 at 11:26
  • signal() might work, but won't stop it closing. It depends what signal it gets by closing the console. – CashCow Jan 28 '14 at 11:26
  • Using a static variable with a destructor seems like the obvious solution, but since the problem isn't really clean, it's hard to say. – James Kanze Jan 28 '14 at 11:27
  • "non-Object-oriented console application" : what does that mean ? If you use C++, you can have objects. Then, you could do what @JamesKanze suggests. – JBL Jan 28 '14 at 11:28
  • You'll have to rely on platform specific APIs. See [this SO thread](http://stackoverflow.com/questions/696117/what-happens-when-you-close-a-c-console-application). – jrok Jan 28 '14 at 11:29
  • Hi! Would the correct title here be "Call function when user clicks [X] on the windows console window" ? – Martin Ba Jan 28 '14 at 11:32
  • 3
    What if the X isn't red? – Jonas Byström Jan 28 '14 at 11:32

2 Answers2

5

When you are on Windows and have a console application running inside the normal console window, and then click on the Close Button ([X]) this will generate a CTRL_CLOSE_EVENT.

You can handle these by installing a Console Event Handler with the SetConsoleCtrlHandler Win32 API function.

Martin Ba
  • 37,187
  • 33
  • 183
  • 337
2

You can try using atexit():

http://www.cplusplus.com/reference/cstdlib/atexit/

Or maybe a destructor of a global object.

selalerer
  • 3,766
  • 2
  • 23
  • 33