WPF Application UI Test Automation – Getting the Main Window

I’ve been looking at testing WPF (Windows Presentation Foundation) applications lately. It took me a while to warm up to WPF apps but now I’m a big fan. UI automation for WPF apps is a new ball game. By far the best approach is to use the Microsoft UI Automation (MUIA) library which, like WPF, is part of the .NET 3.0 Framework. The very first step to automate a WPF application is to get a reference to the main app window (we don’t call it a WinForm any more). There are several approaches possible. One technique is to use the AutmationElement.FindFirst() mehod of the MUIA library. FindFirst accepts parameters which identify the target element to get. Interestingly, when I used Visual Studio 2008 to create a WPF application, by default the application main window does not get a Name attribute in the XAML file which dfines the main window. So, in a default scenario, when the WPF app is built using Visual Studio, no AutomationId propertty is generated for the main window of the app — and so you can use FindFirst() in a natural way. Well the obvious solution is to just manually add a Name property to the main window. Then you can get a reference to the app (named StatCalc in my example in the screenshot below) like:
// launch app here
// get reference to Desktop element
Console.WriteLine("\nLooking for StatCalc main window. . . ");
AutomationElement aeStatCalc =
   new PropertyCondition(AutomationElement.AutomationIdProperty,
if (aeStatCalc == null)
  throw new Exception("Failed to find StatCalc main window");
However, this approach has three significant problems. First, it relies on you having control of the app under test so you can manually add a Name attribute so that an AutomationId property is generated. You may not have such control. Second, this approach assumes there is only a single instance of the app under test running. If there is more than one instance you might get a reference to the wrong instance. Third, this approach doesn’t take any timing issues into account. A complex app may take time to launch and your automation will miss it. For these reasons I conclude that the approach above is not feasible. I have a neat solution and I’m writing up an article for MSDN Magazine.
This entry was posted in Software Test Automation. Bookmark the permalink.

One Response to WPF Application UI Test Automation – Getting the Main Window

  1. Ed says:

    Could you provide a link to your article?

Comments are closed.