- 1 year ago
How to detect when python program is closed by pressing the "X" button
To detect when a Python program is closed by pressing the "X" button (the close button in the window's title bar), you can handle the WM_CLOSE
message using the ctypes
module to interact with the Windows API. Here's an example:
pythonimport ctypes
import ctypes.wintypes
# Define the callback function for handling the WM_CLOSE message
def close_handler(hwnd, msg, wparam, lparam):
print("Program is closing...")
# Perform any necessary cleanup or additional actions here
# ...
# Call the default window procedure to close the program
return ctypes.windll.user32.DefWindowProcW(hwnd, msg, wparam, lparam)
# Register the close handler callback function
WNDPROC = ctypes.WINFUNCTYPE(ctypes.wintypes.LRESULT, ctypes.wintypes.HWND, ctypes.wintypes.UINT, ctypes.wintypes.WPARAM, ctypes.wintypes.LPARAM)
WNDPROC_CALLBACK = WNDPROC(close_handler)
# Set the close handler as the window procedure for the current process
ctypes.windll.user32.SetWindowLongPtrW(ctypes.windll.kernel32.GetConsoleWindow(), ctypes.c_int(-4), ctypes.cast(WNDPROC_CALLBACK, ctypes.c_void_p))
# Run your main program logic here
while True:
# ...
In this example, the close_handler
function is defined as the callback function for handling the WM_CLOSE
message. Inside the function, you can perform any necessary cleanup or additional actions before the program closes. The print
statement is used as an example.
The WNDPROC
and WNDPROC_CALLBACK
variables are used to define the callback function's type and cast it appropriately. Then, the SetWindowLongPtrW
function from the Windows API is called to set the close handler as the window procedure for the current process's console window.
After registering the close handler, you can run your main program logic in the while True
loop or wherever appropriate.
Note that this approach only works for console-based Python programs running in a console window. It won't work for GUI applications or programs running in non-console environments.
Keep in mind that interacting with the Windows API requires proper handling and understanding of the Windows message loop and window procedures. Also, note that this solution is specific to Windows and won't work on other operating systems.