0

I can't find a way to add a callback for when a window is closed - and also not a reliable way to react to newly created windows.

My application creates a few processes using subprocess.Popen. Each process has a visible window. The processes share some events with pyHook, using PumpMessages for this.

I use this method to get a handle to each window: Tim Golden: Find the window for my subprocess
This method first sleeps a bit to wait for the windows' creation, then uses EnumWindows and compares the pid. Ok, this method sometimes works, if given enough time, and sometimes stays idle way to long. Obviously waiting for a notification that a new window was created would be better.

Same goes for closing a window. I guess I can check a handle with IsWindow in the pyHook events, but that doesn't seem right. I haven't found any python examples for this, the msdn examples say WM_CLOSE will be send, but I can't get it to listen for any messages (nothing ever happens, I only see my pyHook events). I'm not even sure if I'm using HookMessage correctly here:

def close_window(hwnd, msg):
    print "closed " + str(hwnd)

window = win32ui.CreateWindowFromHandle(hwnd)
# WM_CLOSE 0x0010
window.HookMessage(close_window,0x0010)

Is there a way to add a callback that gets executed when a process creates a window?
How can I get a callback to be executed when a window is closed?

1 Answer 1

1

The only way I have ever found in doing this, and I have been looking into this for many years now, is to use the Python bindings for the Microsoft active accessibility layer (pyAA). This project is no longer actively maintained, so you will have to build it yourself for your version of Windows, but it is the only way I know of to get this to work.

1
  • @kapex you accepted this answer so I presume this worked for you. I don't suppose you remember what you tried in the end? (Understandably if not given this was 11 years ago)
    – Lou
    Commented Apr 7, 2022 at 8:27

Not the answer you're looking for? Browse other questions tagged or ask your own question.