1

I don't want to deflect the button hit or ignore the close event. I just need to run some cleanup code.

Let me tell you what I've tried so far:

atexit()

_onexit()

SetConsoleCtrlHandler()

~QCoreApplication()

No code set by these is being executed. The process just get killed when I press the X.

I certainly can make a windowed app and solve this, but is there a solution for a console application?

Thanks!

Alvein
  • 167
  • 1
  • 9
  • Related - different lang but may shed some clues cos still Windows and still console - https://stackoverflow.com/q/4646827/4386278 – Asteroids With Wings Jan 26 '21 at 18:11
  • 1
    tl;dr SetConsoleCtrlHandler sounds right - perhaps show a [mcve] of that approach – Asteroids With Wings Jan 26 '21 at 18:11
  • 1
    Mind you, https://social.msdn.microsoft.com/Forums/en-US/abf09824-4e4c-4f2c-ae1e-5981f06c9c6e/windows-7-console-application-has-no-way-of-trapping-logoffshutdown-event?forum=windowscompatibility seems to suggest this has become difficult in "recent" years – Asteroids With Wings Jan 26 '21 at 18:12
  • On another [answer](https://stackoverflow.com/a/12988732/14972751) it's pointed out that close button is not a real window. See [TITLEBARINFOEX](https://learn.microsoft.com/en-us/windows/win32/api/winuser/ns-winuser-titlebarinfoex) structure only stores coordinates of close button. Notice that there's no `HWND`. I say, you could try detecting mouse clicks onto those coordinates. – user814412 Jan 26 '21 at 18:16
  • 2
    *I just need to run some cleanup code.* -- Isn't that what class destructors can handle? Create a class, make a global instance, and in the destructor, put the clean up code there. – PaulMcKenzie Jan 26 '21 at 18:19
  • 2
    `SetConsoleCtrlHandler()` is the correct and official way to detect the console window being closed. However, since Windows 7, the callback is no longer triggered during system logoff/shutdown. So, for that, create a hidden window via `CreateWindow/Ex()` and have it handle `WM_(QUERY)ENDSESSION` messages, or `WM_WTSSESSION_CHANGE` messages from `WTSRegisterSessionNotification()`.. – Remy Lebeau Jan 26 '21 at 18:54
  • 1
    @PaulMcKenzie If `atexit` isn't firing, it stands to reason that destructors aren't either. Instead, the process is being hard-terminated. – Asteroids With Wings Jan 26 '21 at 19:15
  • @RemyLebeau Sounds like a good answer! – Asteroids With Wings Jan 26 '21 at 19:15
  • @Asteroids With Wings, the official sample only works for Ctrl+C. https://learn.microsoft.com/en-us/windows/console/registering-a-control-handler-function – Alvein Jan 26 '21 at 19:16
  • @user814412, instead of going through such complication, I'd create a windowed app – Alvein Jan 26 '21 at 19:17

0 Answers0