繁体   English   中英

UI自动化 - 为另一个应用程序的TextBox设置Text

[英]UI Automation - Set Text for a another application's TextBox

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

这是我的代码:

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);
}

您应首先检查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!");
        }
    }
}

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

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

你可以阅读有关方法:

首先,您应该获得要打开的第二个表单的句柄。 如果它先前已创建并存储为类变量,则使用它,否则在此方法中创建并打开它。

为了能够以其他形式填充文本框,您需要将其访问者设置为公共访问者,或者为其创建公共setter方法。

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);

    // this is the idea, not tested, adjust it to yourself
    var form2 = new SecondForm();
    form2.YourTextBox.Text = newTextBoxValue;
    form2.Show();
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM