I found the following code on StackOverflow:
def getForegroundWindowTitle() -> Optional[str]:
hWnd = windll.user32.GetForegroundWindow()
length = windll.user32.GetWindowTextLengthW(hWnd)
buf = create_unicode_buffer(length + 1)
windll.user32.GetWindowTextW(hWnd, buf, length + 1)
# 1-liner alternative: return buf.value if buf.value else None
if buf.value:
return buf.value
else:
return None
This works great except I was wondering if I could use the PID to achieve the same effect as I have a way to get the PID. Perhaps some way to convert the PID to the window handle? I've tried different functions in the win32 API docs but none work. I'm reluctant to use win32gui because it hasn't been updated in some time.