使用自动化框架在textfield/textbox上设置文本并获取更改事件

don*_*are 9 c# events user-interface input ui-automation

我想在文本字段/文本框元素上使用Mircosoft UI自动化框架设置文本,这意味着AutomationElement来自ControlType.EditControlType.Document.

目前我正在使用TextPattern以从其中一个获取文本AutomationElements:

TextPattern tp = (TextPattern)element.GetCurrentPattern(TextPattern.Pattern);
string text = tp.DocumentRange.GetText(-1).Trim();
Run Code Online (Sandbox Code Playgroud)

但现在我想在中设置一个新文本AutomationElement.我在TextPattern课堂上找不到这方法.所以我试图使用ValuePattern但我不确定这是否是正确的方法:

ValuePattern value = element.GetCurrentPattern(ValuePattern.Pattern) as ValuePattern;
value.SetValue(insertText);
Run Code Online (Sandbox Code Playgroud)

还有其他方法来设置文本值吗?

另一个问题是如何在Edit/ Document元素上更改文本时获取事件?我尝试使用TextChangedEvent但是在更改文本时我没有触发任何事件:

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");
}
Run Code Online (Sandbox Code Playgroud)

Mua*_*lig 9

您可以使用ValuePatern,这是它的方法.从我自己的代码:

ValuePattern etb = EditableTextBox.GetCurrentPattern(ValuePattern.Pattern) as ValuePattern;
etb.SetValue("test");
Run Code Online (Sandbox Code Playgroud)

您可以注册Event使用:

var myEventHandler= 
            new AutomationEventHandler(handler);

Automation.AddAutomationEventHandler(
    SelectionItemPattern.ElementSelectedEvent, // In your case you might want to use another pattern
    targetApp, 
    TreeScope.Descendants, 
    myEventHandler);
Run Code Online (Sandbox Code Playgroud)

handler方法:

private void handler(object src, AutomationEventArgs e) {...}
Run Code Online (Sandbox Code Playgroud)

还有AutomationPropertyChangedEventHandler(Automation.AddAutomationPropertyChangedEventHandler(...)在这种情况下使用)可能有用.

基于MSDN的此示例.