gpt4 book ai didi

c# - 使用自动化框架在文本字段/文本框上设置文本并获取更改事件

转载 作者:太空狗 更新时间:2023-10-29 17:49:44 28 4
gpt4 key购买 nike

我想使用 Mircosoft UI Automation 框架在文本字段/文本框元素上设置文本,这意味着在 ControlType.Edit< 的 AutomationElementControlType.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/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com