Skip to content

Instantly share code, notes, and snippets.

@marvintensuan
Last active June 25, 2021 16:52
Using pywin32 win32gui.IsWindow to check if a Window still exists
'''Using pywin32 to check if a Window still exists.
Requirements:
- pywin32
Problem:
I am presented with a custom Excel XLAM ribbon which has a password-protected backend code.
This ribbon has the functionality to bring out a message box and/or UserForm.
You want Python to execute some functions soon as these message boxes and/or UserForm close.
Resources:
The existing code already make use of `win32gui.EnumWindows`.
Solution:
1. Check if message boxes/UserForm have their own hwnd. They have.
2. Check if it is possible to know whether or not certain hwnd still exists.
Turns out `IsWindow()` is part of Windows API and is available as `win32gui.IsWindow`.
To simulate the code below, have Excel create a sample
message box using the code below:
```vba
Sub main()
MsgBox "Hello World", Title:="FIND ME"
End Sub
```
Do NOT press OK. Run the Python script.
Further improvements:
Do take note that Windows can reuse hwnd.
It is worth exploring if it is possible to
integrate the code in asynchronous processes.'''
from time import sleep
import win32gui
MSGBOX_TITLE = 'FIND ME'
CHECK_INTERVAL = 0.5
def callback(hwnd, custom_list):
custom_list.append((hwnd, win32gui.GetWindowText(hwnd)))
def check_exists(hwnd):
try:
exists = True
while exists:
if win32gui.IsWindow(hwnd):
print('Exists...')
sleep(CHECK_INTERVAL)
else:
exists = False
except KeyboardInterrupt:
raise SystemExit
if __name__ == '__main__':
win32gui.EnumWindows(callback, windows := [])
for handle, title in windows:
if title == MSGBOX_TITLE:
hwnd_target = handle
check_exists(hwnd_target)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment