如何使用Windows UIAutomation点击WPF TextBox并校验屏幕键盘是否弹出
WPF应用UIAutomation触控键盘测试方案
前置依赖
首先在测试项目中添加3个程序集引用:
UIAutomationClientUIAutomationTypesWindowsBase
步骤1:定位并点击目标TextBox
所有操作均基于UIAutomation原生API实现,无需调用WinAPI:
- 获取WPF应用根元素
using System.Windows.Automation; using System.Diagnostics; // 替换为你的WPF应用进程名 Process appProcess = Process.GetProcessesByName("你的WPF应用进程名").FirstOrDefault(); AutomationElement rootAppElement = AutomationElement.FromHandle(appProcess.MainWindowHandle);
- 定位目标TextBox,建议提前在WPF代码中为TextBox设置唯一的
AutomationProperties.AutomationId,提升定位准确性
var textBoxCondition = new AndCondition( new PropertyCondition(AutomationElement.ControlTypeProperty, ControlType.Edit), // 替换为你给TextBox设置的AutomationId new PropertyCondition(AutomationElement.AutomationIdProperty, "TargetTextBoxId") ); AutomationElement targetTextBox = rootAppElement.FindFirst(TreeScope.Descendants, textBoxCondition);
- 触发TextBox点击操作
// 方式1:使用控件点击点触发点击 if (targetTextBox.TryGetClickablePoint(out System.Windows.Point clickPoint)) { System.Windows.Input.Mouse.Click(clickPoint); } // 方式2:使用InvokePattern触发点击,无坐标依赖 if (targetTextBox.TryGetCurrentPattern(InvokePattern.Pattern, out object patternObj)) { (patternObj as InvokePattern)?.Invoke(); } // 等待键盘弹出,可替换为智能等待逻辑避免硬编码 System.Threading.Thread.Sleep(1000);
步骤2:校验屏幕键盘是否弹出
通过UIAutomation直接查询桌面根元素下的触摸键盘窗口即可,系统触摸键盘的窗口类名为固定值IPTip_Main_Window:
AutomationElement desktopRoot = AutomationElement.RootElement; var keyboardCondition = new AndCondition( new PropertyCondition(AutomationElement.ControlTypeProperty, ControlType.Window), new PropertyCondition(AutomationElement.ClassNameProperty, "IPTip_Main_Window"), // 验证窗口可见,未被隐藏/最小化 new PropertyCondition(AutomationElement.IsOffscreenProperty, false) ); AutomationElement touchKeyboard = desktopRoot.FindFirst(TreeScope.Children, keyboardCondition); bool isKeyboardOpened = touchKeyboard != null;
你可以基于isKeyboardOpened的值完成测试断言。
注意事项
- Windows 10/11系统下上述触摸键盘的类名通用,无需额外适配
- 硬等待可替换为循环查询逻辑,最多等待3秒查找键盘元素,提升测试用例稳定性
- 测试前请确保系统触摸键盘功能已开启,无组策略禁用等异常情况
内容的提问来源于stack exchange,提问作者Sergey Lobanov
相关产品推荐
相关产品推荐

