Search code examples
pythonseleniumappiumwinappdriver

How to switch to an already running application using WinAppDriver (Python)


I want to switch between MS Store and Chrome browser. how to switch applications using WinAppDriver?

I was looking into https://github.com/microsoft/WinAppDriver/issues/534, found a few suggestions in C# but unfortunately they are not working with python and updated appium/selenium.

Here is my code to connect to the Root

desired_caps = {}
desired_caps["app"]="Root"
session = webdriver.Remote(command_executor='http://127.0.0.1:4723', desired_capabilities= desired_caps)

print(session.current_window_handle)
#it prints current window handle

Next, I am trying to get all the handlers, which is returning Null,

windows = session.window_handles

Solution

  • I found a workaround, find your desired applications WindowHandle, then directly create session using extracted WindowHandle. Traversing from root is not worthy. I found a lot of people are complaining about how to switch I hope this will help a lot!

    import win32gui
    
    def findWindowHandle():
        handleList = []
        def findit(hwnd,ctx):
            if win32gui.GetWindowText(hwnd) == "Microsoft Store": # check the title
                handleList.append(hwnd)
    
        win32gui.EnumWindows(findit,None)
        return handleList
    
    handle = hex(findWindowHandle()[0])
    print(handle)
    
    
    desired_caps = {}
    desired_caps["appTopLevelWindow"] = handle
    desired_caps["deviceName"]="WindowsPC"
    desired_caps["platformName"]="Windows"
    session = webdriver.Remote(command_executor='http://127.0.0.1:4723', desired_capabilities= desired_caps)