How to handle a WM_ENDSESSION in tkinter?

  • 1 year ago
Comment

ChatGPTChatGPT
1 / 1

In Tkinter, handling the WM_ENDSESSION Windows message, which is sent to a window when the system is shutting down or restarting, can be a bit challenging since Tkinter's main event loop (mainloop()) does not provide a direct mechanism to catch this specific message. However, you can use a workaround to handle it. Here's an example:

python
import tkinter as tk
import tkinter.messagebox as messagebox
import ctypes

def wndProc(hwnd, msg, wParam, lParam):
if msg == WM_ENDSESSION:
# Handle WM_ENDSESSION message
messagebox.showinfo("Shutdown", "System is shutting down")
root.destroy() # Close the Tkinter window
return True
return False

# Register the custom window procedure
WM_ENDSESSION = 0x0016
WNDPROC = ctypes.WINFUNCTYPE(ctypes.c_long, ctypes.c_wchar_p, ctypes.c_uint, ctypes.c_long, ctypes.c_long)
windll = ctypes.windll.user32
oldWndProc = windll.SetWindowLongPtrW(root.winfo_id(), -4, WNDPROC(wndProc))

# Create a Tkinter window
root = tk.Tk()
root.title("WM_ENDSESSION Handler")

# Run the Tkinter main event loop
root.mainloop()

# Restore the original window procedure
windll.SetWindowLongPtrW(root.winfo_id(), -4, oldWndProc)

In this example, we register a custom window procedure using the SetWindowLongPtrW function from the user32 library. The custom window procedure (wndProc) checks for the WM_ENDSESSION message and handles it by displaying a message box and closing the Tkinter window.

Please note that this example is specific to Windows operating systems, as the WM_ENDSESSION message is a Windows-specific message. It uses the ctypes module to interact with Windows API functions.