Search code examples
c#microsoft-ui-automation

How to make sure that button has been clicked?


Is there a simple way to check if my OK button was pressed? Most of the times it is working perfectly, but 1 in 100 it fails:

AutomationElement rl = SomeMethod();
if (rl.Current.Name == "OK" && rl.Current.ControlType == ControlType.Button)
{
    InvokePattern click = (InvokePattern)rl.GetCurrentPattern(InvokePattern.Pattern);
    click.Invoke();
}

I wonder why.


Solution

  • To get a notification after your button has been pressed you can register an AutomationEventHandler via

    Automation.AddAutomationEventHandler(InvokePattern.InvokedEvent, AutomationElement yourAE,TreeScope.Element, new AutomationEventHandler(OnStartInvoke));
    
    private static void OnStartInvoke(object src, AutomationEventArgs e)
    {
        //logic
    }
    

    you could use this in order to verify that the button has been clicked also. Invoke the button in a scheduler (with a certain timeout) until you enter your OnStartInvoke.