The application I am writing coded UI tests for has a window where part of the window title is based on a random filename generated for a temporary file, so the test can only know the static part of the window title.
Occasionally, when no other windows are open, the test runs fine. It is a bit problematic when other windows are open, however. If the other windows have similar controls, which window the test picks to work in is unpredictable.
I've narrowed it down to this: When searching for a control, the Coded UI Test uses search properties and a tree-like structure of controls. If it can't find an exact match it finds a close match (so it can't find the exact window title name, it excludes that and keeps searching for a window that matches any other given properties) which is why it works with controls in other windows.
The solution is really to give it more search properties to work with. One method I use is to add a property using a PropertyExpression and pass it PropertyExpressionOperator.Contains.
As an example, I recorded opening MS Word and closing it. This generates a control in the UIMap, and in its constructor is the following:
this.SearchProperties[WinWindow.PropertyNames.Name] = "Document1 - Microsoft Word";
this.SearchProperties[WinWindow.PropertyNames.ClassName] = "OpusApp";
Rather, the first line should be:
this.SearchProperties.Add(new PropertyExpression(WinWindow.PropertyNames.Name, "Microsoft Word", PropertyExpressionOperator.Contains));