我有两种形式。当单击其中一个按钮时,我想打开另一个按钮并在其中填充一个文本框。我尝试使用下面的代码,但它给出了一个错误,指出“不支持的模式”。
这是我的代码:
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
图案:
- If the
ValuePattern
模式可用,使用其SetValue
method.
- Else use one of the following solutions:
- 将焦点集中在控制和使用上
SendKeys
清除和设置文本。
- Or Use
SendMessage
并且寄出WM_SETTEXT
设置文本的消息,
Example
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;
您可以阅读有关该方法的信息:
- 使用 UI 自动化将内容添加到文本框 https://learn.microsoft.com/en-us/dotnet/framework/ui-automation/add-content-to-a-text-box-using-ui-automation
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)