UI 自动化 - 为另一个应用程序的文本框设置文本

sae*_*eed 3 .net c# ui-automation winforms

我有两种形式。当单击其中一个按钮时,我想打开另一个按钮并在其中填充一个文本框。我尝试使用下面的代码,但它给出了一个错误,指出“不支持的模式”。

这是我的代码:

private void button1_Click(object sender, EventArgs e)
{
    string automationId = "Form1";
    string newTextBoxValue = "user1";
    var condition = new PropertyCondition(AutomationElement.AutomationIdProperty, automationId);
    var textBox = AutomationElement.RootElement.FindFirst(TreeScope.Subtree, condition);
    ValuePattern vPattern = (ValuePattern)textBox.GetCurrentPattern(ValuePattern.Pattern);
    vPattern.SetValue(newTextBoxValue);
}
Run Code Online (Sandbox Code Playgroud)

Rez*_*aei 6

您应该首先检查模式的可用性ValuePattern

  • 如果该ValuePattern模式可用,请使用其SetValue方法。
  • 否则使用以下解决方案之一:
    1. 将焦点设置到控件并用于SendKeys清除和设置文本。
    2. 或者使用SendMessage并发送WM_SETTEXT消息来设置文本,

例子

var notepad = System.Diagnostics.Process.GetProcessesByName("notepad").FirstOrDefault();
if (notepad != null)
{
    var root = AutomationElement.FromHandle(notepad.MainWindowHandle);
    var element = root.FindAll(TreeScope.Subtree, Condition.TrueCondition)
                        .Cast<AutomationElement>()
                        .Where(x => x.Current.ClassName == "Edit" &&
                                    x.Current.AutomationId == "15").FirstOrDefault();
    if (element != null)
    {
        if (element.TryGetCurrentPattern(ValuePattern.Pattern, out object pattern))
        {
            ((ValuePattern)pattern).SetValue("Something!");
        }
        else
        {
            element.SetFocus();
            SendKeys.SendWait("^{HOME}");   // Move to start of control
            SendKeys.SendWait("^+{END}");   // Select everything
            SendKeys.SendWait("{DEL}");     // Delete selection
            SendKeys.SendWait("Something!");

           // OR 
           // SendMessage(element.Current.NativeWindowHandle, WM_SETTEXT, 0, "Something!");
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

如果使用,SendMessage请确保将以下声明添加到类中:

[System.Runtime.InteropServices.DllImport("User32.dll")]
static extern int SendMessage(int hWnd, int uMsg, int wParam, string lParam);
const int WM_SETTEXT = 0x000C;
Run Code Online (Sandbox Code Playgroud)

您可以阅读有关该方法的信息: