You can use the win32gui module to do that. First you need to get a valid handle on your window. You can use the win32gui.FindWindow
if you know the window class name or the exact title. If not, you can enumerate the windows with the win32gui.EnumWindows
and try to find the right one.
Once you have the handle, you can call the win32gui.SetForegroundWindow
with the handle. It will activate the window and will be ready for getting your keystrokes.
See an example below. I hope it helps
import win32gui
import re
class WindowMgr:
"""Encapsulates some calls to the winapi for window management"""
def __init__ (self):
"""Constructor"""
self._handle = None
def find_window(self, class_name, window_name=None):
"""find a window by its class_name"""
self._handle = win32gui.FindWindow(class_name, window_name)
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)
def set_foreground(self):
"""put the window in the foreground"""
win32gui.SetForegroundWindow(self._handle)
w = WindowMgr()
w.find_window_wildcard(".*Hello.*")
w.set_foreground()
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…