[英]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. 我在Python中有一个常规的控制台窗口(Windows 8.1),我想更改close / X按钮的功能。 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. 您可以通过使用SetConsoleCtrlHandler指定指定用于Ctrl-C,Ctrl-Break,控制台退出和系统关闭事件的函数来拦截控制台关闭事件。 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: 如果这是在控制台中运行(使用Python 3),并且您按了Ctrl-C,则应该得到以下内容:
c:\src>python python\setconsolectrl.py
0
HANDLER
1
exiting... 0
where the 0 was the value for CTRL_C_EVENT . 其中0是CTRL_C_EVENT的值。 For console exit we should get 2 set here, so we can tell what kind of event was generated.
对于控制台出口,我们应该在此处设置2,以便我们可以判断生成了哪种事件。
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. 如果您运行此程序并按红色大X来关闭控制台,则可以看到控制台被销毁时正在打印HANDLER。 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.
您应该在文件中添加一些日志记录,以确保真正调用了所有清理操作,但这看起来应该可以解决您的问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.