Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

On Windows, how do I get the hwnd of the window? #1115

Answered by RexBarker
tqphan asked this question in Q&A
Discussion options

On Windows, how do I get the hwnd of the window?

You must be logged in to vote

This is a WindowMngr class that finds the name of your window by the title. Works if you have only one window with that name.

import re
import win32gui
import win32com.client
class WindowMgr:
 """Encapsulates calls to the winapi for window management
 Based on:
 - https://stackoverflow.com/questions/2090464/python-window-activation
 - https://stackoverflow.com/questions/14295337/win32gui-setactivewindow-error-the-specified-procedure-could-not-be-found
 """
 def __init__(self):
 self._handle = None
 @property
 def handle(self):
 return self._handle
 def _window_enum_callback(self, hwnd, wildcard):
 """Pass to win32gui.EnumWindows() to c...

Replies: 1 comment

Comment options

This is a WindowMngr class that finds the name of your window by the title. Works if you have only one window with that name.

import re
import win32gui
import win32com.client
class WindowMgr:
 """Encapsulates calls to the winapi for window management
 Based on:
 - https://stackoverflow.com/questions/2090464/python-window-activation
 - https://stackoverflow.com/questions/14295337/win32gui-setactivewindow-error-the-specified-procedure-could-not-be-found
 """
 def __init__(self):
 self._handle = None
 @property
 def handle(self):
 return self._handle
 def _window_enum_callback(self, hwnd, wildcard):
 """Pass to win32gui.EnumWindows() to check all the opened windows"""
 if re.match(wildcard, str(win32gui.GetWindowText(hwnd))) is not None:
 self._handle = hwnd
 def find_window_wildcard(self, wildcard):
 """find a window whose title matches the wildcard regex"""
 self._handle = None
 win32gui.EnumWindows(self._window_enum_callback, wildcard)
 return self

Use it like this:
handle = WindowMgr().find_window_wildcard("My Nice App").handle

You must be logged in to vote
0 replies
Answer selected by tqphan
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants

AltStyle によって変換されたページ (->オリジナル) /