Home > Enterprise >  Python win32gui application - trying to quit from external thread
Python win32gui application - trying to quit from external thread

Time:10-11

I have a python application that uses a tray icon created through win32 to control a tkinter GUI. The tray icon can issue commands to the tkinter GUI (hide/show/close/etc.), but since it's in a separate thread it won't accept commands from the tkinter GUI (such as exiting the program).

I found a response here that outlines the process of accessing the tray icon's thread: How to DestroyWindow from remote thread?

  1. Get thread ID of the tray icon from GetWindowThreadProcessId()
  2. Install a message hook with SetWindowsHookEx()
  3. Use message hook to trigger the exit command on the tray icon thread

This sounds straightforward, but I am not clear on how to implement it in practice.

Step 1 is easy:

tid, pid = win32process.GetWindowThreadProcessId(self.hwnd)

Could someone provide an example/guidance on the format of steps 2 and 3, please?

CodePudding user response:

The solution as suggested by IInspectable in the comments was to directly use a PostMessage like so:

win32gui.PostMessage(self.hwnd, win32con.WM_CLOSE, 0, 0)

This allowed the tkinter GUI to tell the win32 tray icon to quit without encountering thread-related access errors.

  • Related