gpt4 book ai didi

python - 使用Python 3阻止Windows 10关闭

转载 作者:行者123 更新时间:2023-12-03 11:10:36 24 4
gpt4 key购买 nike

有什么方法可以防止Windows使用Python关闭我的系统。因此,当我的Python脚本运行时,我无法关闭系统吗?

最佳答案

就在这里。
从Windows文档

Shutdown Notifications

Applications with a window and message queuereceive shutdown notifications through the WM_QUERYENDSESSION andWM_ENDSESSION messages. These applications should return TRUE toindicate that they can be terminated. Applications should not blocksystem shutdown unless it is absolutely necessary. Applications shouldperform any required cleanup while processing WM_ENDSESSION.Applications that have unsaved data could save the data to a temporarylocation and restore it the next time the application starts. It isrecommended that applications save their data and state frequently;for example, automatically save data between save operations initiatedby the user to reduce the amount of data to be saved at shutdown.Console applications receive shutdown notifications in their handlerroutines. To register a console handler, use the SetConsoleCtrlHandlerfunction. Service applications receive shutdown notifications in theirhandler routines. To register a service control handler, use theRegisterServiceCtrlHandlerEx function.

Blocking Shutdown

If an application must block a potential system shutdown, it can call theShutdownBlockReasonCreate function. The caller provides a reasonstring that will be displayed to the user. The reason string should beshort and clear, providing the user with the information necessary todecide whether to continue shutting down the system.


因此您必须截获WM_QUERYENDSESSION消息并返回False。
并进行了一些网络搜索,我发现了关于如何在python中拦截WM_QUERYENDSESSION的讨论:

if you've built an app with a message loop, you can receive theWM_QUERYENDSESSION message. If you want to have a GUI, most GUIlibraries will probably wrap this up in their own way. If you don'tneed a GUI, your simplest solution is probably to use PyWin32.Somewhere in the docs there's a tutorial on creating a hidden windowand writing a simple message loop. Just do that on the main thread,and do your real work on a background thread, and signal yourbackground thread when a WM_QUERYENDSESSION message comes in.

Or, much more simply, just use SetConsoleCtrlHandler (again throughPyWin32). This can also catch ^C, ^BREAK, and the user closing yourconsole, as well as the logoff and shutdown messages thatWM_QUERYENDSESSION catches. More importantly, it doesn't require amessage loop, so if you don't have any other need for one, it's a lotsimpler.


我无法使用代码段,因为我无法访问Windows pc,并且我也不想在未经测试的情况下共享代码,但是我希望我指出了您应该寻找的内容。

关于python - 使用Python 3阻止Windows 10关闭,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54830926/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com