CJC
CJC

Reputation: 400

Focus child window in Python win32gui

I'm using Python to send keyboard commands to other programs. I have a working solution but I'm looking to improve it.

The other programs are Genesys CCPulse reports and I have four different instances running at the same time. Each instance has it's own main window and then a number of child windows inside (up to 30).

Thanks to this post Python Window Activation I have been able to switch between the main windows and get the one I need in the foreground. I'm currently using keyboard commands to send menu shortcuts to change focus to the child windows and save them.

I'd like to avoid the menu navigation and just activate each child window, then send the commands to save them. Another post EnumChildWindows not working in pywin32 has got me the list of handles for the child windows.

Ideally I would like to continue using win32gui if possible as the rest of the code is working.

Current code is

import win32gui
import re

class WindowMgr:
    #set the wildcard string you will search for
    def find_window_wildcard(self, wildcard):
        self._handle = None
        win32gui.EnumWindows(self.window_enum_callback, wildcard)

    #enumurate through all the windows until you find the one you need
    def window_enum_callback(self, hwnd, wildcard):
        if re.match(wildcard, str(win32gui.GetWindowText(hwnd))) != None:
            self._handle = hwnd ##pass back the id of the window

    #as a separate function, set the window to the foreground    
    def set_foreground(self):
        win32gui.SetForegroundWindow(self._handle)

    #extra function to get all child window handles
    def get_child_handles(self):
        win32gui.EnumChildWindows(self._handle, add_to_list, None)

    #final function to send the commands in
    def flash_window(self):
        for c_hwnd in child_list:
            print((self._handle),(c_hwnd),(win32gui.GetWindowText(c_hwnd))) #prove correct child window found
            #send command1#
            #send command2#
            #send command3#

#seprate fundction to collect the list of child handles
def add_to_list(hwnd, param):
    if win32gui.GetWindowText(hwnd)[:3] == "IWD":
        child_list.append(hwnd)

child_list=[]
w = WindowMgr()

w.find_window_wildcard(".*Sales*")
w.set_foreground()
w.get_child_handles()
w.flash_window()

Upvotes: 1

Views: 5304

Answers (1)

CJC
CJC

Reputation: 400

Just found the answer to this

    def flash_window(self):
    for c_hwnd in child_list:
        win32gui.BringWindowToTop(c_hwnd)

It's the BringWindowToTop command that will activate each child window in turn. I can then go on to issue whatever commands I want to each window.

Upvotes: 2

Related Questions