我想使用 Mircosoft UI Automation 框架在文本字段/文本框元素上设置文本,这意味着在 ControlType.Edit< 的
或 AutomationElement
上ControlType.Document
。
目前我正在使用 TextPattern
从这些 AutomationElements
之一获取文本:
TextPattern tp = (TextPattern)element.GetCurrentPattern(TextPattern.Pattern);
string text = tp.DocumentRange.GetText(-1).Trim();
但现在我想在 AutomationElement
中设置一个新文本。我在 TextPattern
类中找不到此方法。所以我正在尝试使用 ValuePattern
但我不确定这是否是正确的方法:
ValuePattern value = element.GetCurrentPattern(ValuePattern.Pattern) as ValuePattern;
value.SetValue(insertText);
还有其他方法可以设置文本值吗?
另一个问题是,当 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");
}
最佳答案
您可以使用 ValuePattern,这是实现它的方法。来 self 自己的代码:
ValuePattern etb = EditableTextBox.GetCurrentPattern(ValuePattern.Pattern) as ValuePattern;
etb.SetValue("test");
您可以使用以下方式注册到Event
:
var myEventHandler=
new AutomationEventHandler(handler);
Automation.AddAutomationEventHandler(
SelectionItemPattern.ElementSelectedEvent, // In your case you might want to use another pattern
targetApp,
TreeScope.Descendants,
myEventHandler);
handler
方法:
private void handler(object src, AutomationEventArgs e) {...}
还有一个很有用的 AutomationPropertyChangedEventHandler
(在这种情况下使用 Automation.AddAutomationPropertyChangedEventHandler(...)
)。
基于此sample来自 MSDN。
关于c# - 使用自动化框架在文本字段/文本框上设置文本并获取更改事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10720162/