Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
325 views
in Technique[技术] by (71.8m points)

c# - set text on textfield / textbox with the automation framework and get the change event

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");
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...