javaseleniumwinappdriver

How to switch focus between windows using WinAppDriver Java


I am new to windows automation using win app driver. Our application is developed with chromium browser and we are using win app diver to automate since the main app we are trying to open is windows based. When I click on Ok button opens another window(Window B). I have 2 windows opened window 1 and window 2. I need to perform actions on both the windows for that I need to shift the focus between two windows. When I use getwindowhandles() method I am getting number of windows opened as 1. How can I switch between windows using winapp driver. Appreciate your help. Thanks


Solution

  • I am using in my code:

     this.driver.SwitchTo().Window(this.driver.WindowHandles[0]);
    

    However, I do not expect this to work in your case, as your number of open windows is 1, than means that there is no second window to switch to. So in your case you can use root session in order to attach to your window:

     AppiumOptions rootSessionOptions = new AppiumOptions();
    rootSessionOptions.AddAdditionalCapability("app", "Root");
    rootSessionOptions.AddAdditionalCapability("deviceName", "WindowsPC");
    _driver = new WindowsDriver<WindowsElement>(new Uri("http://127.0.0.1:4723"), rootSessionOptions);
    _driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(5);
    
    var VSWindow = _driver.FindElementByName("Your project name without .csproj - Microsoft Visual Studio");
    var VSTopLevelWindowHandle = VSWindow.GetAttribute("NativeWindowHandle");
    VSTopLevelWindowHandle = (int.Parse(VSTopLevelWindowHandle)).ToString("x");
    
    AppiumOptions VisualStudioSessionOptions = new AppiumOptions();
    VisualStudioSessionOptions.AddAdditionalCapability("appTopLevelWindow", VSTopLevelWindowHandle);
    _driver = new WindowsDriver<WindowsElement>(new Uri("http://127.0.0.1:4723"), VisualStudioSessionOptions);
    
    _driver.SwitchTo().Window(_driver.WindowHandles[0]);
    

    Reference:
    https://github.com/microsoft/WinAppDriver/issues/978
    OpenQA.Selenium.WebDriverException: [windowHandle] is not a top level window handle solution