I am doing some experimentation with Windows Automation. It is recommended not to use the System.Windows.Automation managed code anymore due to updated patterns in windows 7 & 8 and to use the new COM library. I have found a wrapper called UIAComWrapper on NuGet. I have a piece of code below that invokes a login button on a window. I have tried invoking on some other windows with buttons as well. When using the System.Windows.Automation library the code works fine but when using the UIAComWrapper I get an exception 2-3 seconds after it has successfully invoked the button. Here is the code:
static void Main(string[] args)
{
Automation.AddAutomationEventHandler(WindowPattern.WindowOpenedEvent, AutomationElement.RootElement, TreeScope.Subtree, (sender, e) =>
{
AutomationElement src = sender as AutomationElement;
if (src != null && src.Current.Name == "Login Tester")
{
Console.WriteLine("Class : " + src.Current.ClassName);
Console.WriteLine("Title : " + src.Current.Name);
Console.WriteLine("Handle : " + src.Current.NativeWindowHandle);
Console.WriteLine("ProcessId : " + src.Current.ProcessId);
Console.WriteLine("ControlType : " + src.Current.ControlType);
Console.WriteLine("AutomationId : " + src.Current.AutomationId);
Condition conditions = new AndCondition(
new PropertyCondition(AutomationElement.IsEnabledProperty, true),
new PropertyCondition(AutomationElement.ControlTypeProperty, ControlType.Button)
);
AutomationElementCollection elementCollection = src.FindAll(TreeScope.Children, conditions);
foreach (AutomationElement ae in elementCollection)
{
if (ae.Current.AutomationId == "btnLogin")
{
InvokePattern ip = ae.GetCurrentPattern(InvokePattern.Pattern) as InvokePattern;
ip.Invoke();
}
}
}
});
Console.ReadLine();
}
}
And here is the exception:
Error HRESULT E_FAIL has been returned from a call to a COM component.
And here is the stacktrace:
at UIAutomationClient.IUIAutomationInvokePattern.Invoke()
at System.Windows.Automation.InvokePattern.Invoke() in d:\dev\UIAComWrapper\UiaComWrapper\InvokePattern.cs:line 37
at uiacomwrapperexperimentation2.Program.<>c.<Main>b__0_0(Object sender, AutomationEventArgs e) in C:\Users\****\Documents\Visual Studio 2017\Projects\uiacomwrapperexperimentation2\uiacomwrapperexperimentation2\Program.cs:line 40
at UIAComWrapperInternal.BasicEventListener.UIAutomationClient.IUIAutomationEventHandler.HandleAutomationEvent(IUIAutomationElement sender, Int32 eventId) in d:\dev\UIAComWrapper\UiaComWrapper\ClientEventList.cs:line 111
I have read some posts that say this error could be due to project cache and have tried those solutions with no avail. Here is the Git for the wrapper https://github.com/TestStack/UIAComWrapper