我有两种形式。当单击其中一个按钮时,我想打开另一个按钮并在其中填充一个文本框。我尝试使用下面的代码,但显示“不受支持的模式”错误。
这是我的代码:
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);
}
答案 0 :(得分:2)
您应该首先检查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;
您可以阅读有关方法:
答案 1 :(得分:1)
首先,您应该获得要打开的第二个表单的句柄。如果以前已创建它并将其存储为类变量,则可以使用它,否则,请在此方法中创建它并打开它。
为了使您能够以另一种形式填充文本框,您需要将其访问器设置为public,或者为其创建公共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();
}