简体   繁体   中英

How do I change what the X button does on the Windows console window?

I have a regular console window (Windows 8.1) in Python and I want to change what the close/X button does. When the game ends, it needs to do some clean up and stuff like that, so how do I override what it does?

You can intercept the console close event by using SetConsoleCtrlHandler to specify a function that is called for Ctrl-C, Ctrl-Break, console exit and system shutdown events. For the console exit event you cannot prevent the console from being destroyed but you can intercept the event and run some code. For example:

import sys
import time
import win32api

forever = True
handled_ctrl_type = None

def handler(ctrl_type):
    global forever, handled_ctrl_type
    forever = False
    handled_ctrl_type = ctrl_type
    print("HANDLER")
    return True

def main(args = None):
    win32api.SetConsoleCtrlHandler(handler, True)
    n = 0
    while forever:
        time.sleep(1)
        print(n)
        n = n + 1
    print("exiting...", handled_ctrl_type)
    return 0

if __name__ == '__main__':
    sys.exit(main())

If this is run (using Python 3) in a console and you hit Ctrl-C you should get something like this:

c:\src>python python\setconsolectrl.py
0
HANDLER
1
exiting... 0

where the 0 was the value for CTRL_C_EVENT . For console exit we should get 2 set here, so we can tell what kind of event was generated.

If you run this and hit the big red X to close the console, you can just see HANDLER being printed as the console gets destroyed. You should add some logging to a file to ensure all your cleanup is really getting called but this looks like it should solve your question.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM