Set text to text box / text box using automation frame and get change event

I want to set text in a textfield / textbox element using the Mircosoft UI Automation framework, which means from ControlType.Edit or ControlType.Document .

I'm currently using TextPattern to get 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 new text in AutomationElement . I cannot find a method for this in the TextPattern class. So I'm trying to use ValuePattern , but I'm not sure if this is the correct way:

 ValuePattern value = element.GetCurrentPattern(ValuePattern.Pattern) as ValuePattern; value.SetValue(insertText); 

Is there any other way to set a text value?

Another question: how can I get an event when the text was changed on an Edit / Document element? I tried using TextChangedEvent , but I don't get any events when the text changes:

 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"); } 
+7
source share
1 answer

You can use ValuePatern, this is the way to do it. From my own code:

 ValuePattern etb = EditableTextBox.GetCurrentPattern(ValuePattern.Pattern) as ValuePattern; etb.SetValue("test"); 

You can register for an 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) {...} 

In this case, AutomationPropertyChangedEventHandler also exists (use Automation.AddAutomationPropertyChangedEventHandler(...) ).

Based on this sample from MSDN.

+6
source

All Articles