The FindWindow API provides another way to obtain an instance of a window. The API allows the user to obtain a running instance of a window without intercepting the WindowOpened event. This technique is useful when you can't intercept an event, or when you start the desktop agent after the window is already open.
When searching for a window, you need to provide the window type. The window type is used to locate the window using the binding attributes of this type, and to create a new instance of this type. Each time the FindWindow API is called, a new instance is created. Thus, if there are events you want to register on this window, you need to register them on the new instance.
You can use this API either on ServiceBase or on Window. Calling the API on ServiceBase will look for top level windows, while calling on Window will search for windows that are owned by the receiver window.
public T FindWindow<T>(TimeSpan timeout = new TimeSpan(), Func<Window,bool> predicate = null ) where T : Window |
•timeout (optional): Defines the amount of time to wait until the window is found. If no window is found within this timespan, null is returned.
•predicate (optional): A Lambda expression that is used when we want to differentiate the matched window according to some runtime condition.
Note: When using a predicate, use the MainWindowTitle property, not the Name property. For example: |
Due to a Watin Library issue, the FindWindow API needs to be run under STAThreadPool (single thread apartment). Otherwise, it may throw an exception.
The following example finds a Web main window according to the URL displayed in the browser:
IEwebMainWindow ieMain = null; STAThreadPool.StartNewTask(() => ieMain = srvc.FindWindow<IEMainWindow>(Timespan.FromSeconds(20))); |