我想阻止Windows(xp和7)关闭。 为此,我似乎必须拦截WM_QUERYENDSESSION消息并返回False。
好的我必须更正我的陈述,此程序在Windows 7下工作正常,但在Windows 7嵌入式标准Service Pack 1上它不会阻止关机!
import ctypes
from ctypes import c_long, c_int, c_wchar_p
import time
import win32api
import win32con
import win32gui
import win32process
oldWndProc = None
def wndproc(hWnd, msg, wParam, lParam):
print("wndproc received message: %s" % msg)
if (msg == win32con.WM_QUERYENDSESSION):
print("wndproc received WM_QUERYENDSESSION")
return 0
# Pass all messages to the original WndProc
return win32gui.CallWindowProc(oldWndProc, hWnd, msg, wParam, lParam)
if __name__ == "__main__":
try:
# Create a window just to be able to receive WM_QUERYENDSESSION messages
win32api.SetLastError(0)
hinst = win32api.GetModuleHandle(None)
messageMap = {}
wndclass = win32gui.WNDCLASS()
wndclass.hInstance = hinst
wndclass.lpszClassName = "PreventShutdownWindowClass"
wndclass.lpfnWndProc = messageMap
myWindowClass = win32gui.RegisterClass(wndclass)
hwnd = win32gui.CreateWindowEx(win32con.WS_EX_LEFT,
myWindowClass,
"PreventShutdownWindow",
0,
0,
0,
win32con.CW_USEDEFAULT,
win32con.CW_USEDEFAULT,
0,
0,
hinst,
None)
print 'CreateWindowEx: ' + str(hwnd)
print 'CreateWindowEx last error: ' + str(win32api.GetLastError())
print ''
# Set WndProc
win32api.SetLastError(0)
WndProcType = ctypes.WINFUNCTYPE(c_int, c_long, c_int, c_int, c_int)
newWndProc = WndProcType(wndproc)
oldWndProc = ctypes.windll.user32.SetWindowLongW( hwnd, win32con.GWL_WNDPROC, newWndProc )
print 'SetWindowLong: ' + str(oldWndProc)
print 'SetWindowLong last error: ' + str(win32api.GetLastError())
print ''
# We provide a reason for the shutdown prevention
win32api.SetLastError(0)
ret = ctypes.windll.user32.ShutdownBlockReasonCreate(hwnd, c_wchar_p("PreventShutdown running which prevents shutdown"))
print 'ShutdownBlockReasonCreate: ' + str(ret)
print 'ShutdownBlockReasonCreatelast error: ' + str(win32api.GetLastError())
print ''
# We elevate the program to be asked as soon as possible to inhibit shutdown
win32api.SetLastError(0)
win32process.SetProcessShutdownParameters(0x4FF, win32con.SHUTDOWN_NORETRY)
print 'SetProcessShutdownParameters last error: ' + str(win32api.GetLastError())
print ''
except Exception, e:
print("Exception: %s" % str(e))
while True:
win32gui.PumpWaitingMessages()
time.sleep(1)