用python3阻止windows10关闭

2024-09-28 15:32:38 发布

您现在位置:Python中文网/ 问答频道 /正文

有没有办法阻止Windows用Python关闭我的系统。所以我不能在Python脚本运行时关闭系统?在


Tags: 脚本windows系统关闭系统办法
1条回答
网友
1楼 · 发布于 2024-09-28 15:32:38

是的,有。在

从windows文档

Shutdown Notifications

Applications with a window and message queue receive shutdown notifications through the WM_QUERYENDSESSION and WM_ENDSESSION messages. These applications should return TRUE to indicate that they can be terminated. Applications should not block system shutdown unless it is absolutely necessary. Applications should perform any required cleanup while processing WM_ENDSESSION. Applications that have unsaved data could save the data to a temporary location and restore it the next time the application starts. It is recommended that applications save their data and state frequently; for example, automatically save data between save operations initiated by the user to reduce the amount of data to be saved at shutdown. Console applications receive shutdown notifications in their handler routines. To register a console handler, use the SetConsoleCtrlHandler function. Service applications receive shutdown notifications in their handler routines. To register a service control handler, use the RegisterServiceCtrlHandlerEx function.

Blocking Shutdown

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

所以您必须截获WM\u QUERYENDSESSION消息并返回False。在

在做一些网络搜索时,我发现了一个关于如何拦截python中WM_QUERYENDSESSION的讨论:

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

Or, much more simply, just use SetConsoleCtrlHandler (again through PyWin32). This can also catch ^C, ^BREAK, and the user closing your console, as well as the logoff and shutdown messages that WM_QUERYENDSESSION catches. More importantly, it doesn't require a message loop, so if you don't have any other need for one, it's a lot simpler.

我无法帮助代码片段,因为我无法访问windows pc,也不想在未经测试的情况下共享代码,但我希望我能为您指出应该查找的内容。在

相关问题 更多 >