Search code examples
automated-testsjscripttestcomplete

How to center a WPF window on screen from TestComplete tests?


I'm automating tests for a WPF application using TestComplete 9 and JScript. How can I position a WPF window to the center of the screen from my test scripts? Is there any built-in function for that?


Solution

  • In TestComplete tests, you can move windows by using the Position method. You can calculate the centered position of a window based on the desktop resolution (Sys.Desktop.Width and Sys.Desktop.Height) and the window size (.Width and .Height):

    var wnd = Sys.Process("notepad").Window("Notepad"); // Replace with your window reference
    
    var x = (Sys.Desktop.Width - wnd.Width) / 2;
    var y = (Sys.Desktop.Height - wnd.Height) / 2; 
    wnd.Position(x, y, wnd.Width, wnd.Height);
    

    This is for one monitor. If you have several monitors, adjust the code appropriately. For example, if you have two monitors in horizontal arrangement, use:

    var x = (Sys.Desktop.Width / 2 - wnd.Width) / 2;