[英]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
方法。 SendKeys
清除和设置文本。 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.