I want to set a text on a textfield / textbox element with the Mircosoft UI Automation framework, that means on a AutomationElement from the ControlType.Edit or ControlType.Document.
At the moment i'm using the TextPattern to get the text from one of these AutomationElements:
TextPattern tp = (TextPattern)element.GetCurrentPattern(TextPattern.Pattern);
string text = tp.DocumentRange.GetText(-1).Trim();
But now I want to set a new text in the AutomationElement. I can't find a method for this in the TextPattern class. So I'm trying to use the ValuePattern but I'm not sure if that's the right way to do it:
ValuePattern value = element.GetCurrentPattern(ValuePattern.Pattern) as ValuePattern;
value.SetValue(insertText);
Is there an other way to set the text value?
An other question is how can I get an event when the text was changed on a Edit / Document element? I tried to use the TextChangedEvent but i don't get any events fired when changing the text:
AutomationEventHandler ehTextChanged = new AutomationEventHandler(text_event);
Automation.AddAutomationEventHandler(TextPattern.TextChangedEvent, element, TreeScope.Element, ehTextChanged);
private void text_event(object sender, AutomationEventArgs e)
{
    Console.WriteLine("Text changed");
}
                You can use the ValuePatern, it's the way to do it. From my own code :
ValuePattern etb = EditableTextBox.GetCurrentPattern(ValuePattern.Pattern) as ValuePattern;
etb.SetValue("test");
You can register to Event using:
var myEventHandler= 
            new AutomationEventHandler(handler);
Automation.AddAutomationEventHandler(
    SelectionItemPattern.ElementSelectedEvent, // In your case you might want to use another pattern
    targetApp, 
    TreeScope.Descendants, 
    myEventHandler);
And the handler method:
private void handler(object src, AutomationEventArgs e) {...}
There is also an AutomationPropertyChangedEventHandler (use Automation.AddAutomationPropertyChangedEventHandler(...) in this case) that can be useful.
Based on this sample from MSDN.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With