如何无需先查找App,通过AutomationElement或句柄获取TestStack.White Window对象?
嘿Dan,我之前也遇到过这个头疼的问题——明明手里握着窗口句柄或者AutomationElement,却没法直接拿到TestStack.White的Window对象,毕竟它的相关构造函数都是protected的。不过我找到了两个挺简便的办法,给你参考下:
方法一:用反射直接调用protected构造函数
这应该是最直接的方式,不用额外写类,直接通过反射获取Window的非公开构造函数,传入你的句柄或AutomationElement就行:
如果你有窗口句柄(IntPtr):
using System.Reflection; using TestStack.White; using TestStack.White.UIItems.WindowItems; // 获取Window类的非公开构造函数(接受IntPtr和Desktop) var windowConstructor = typeof(Window).GetConstructor( BindingFlags.NonPublic | BindingFlags.Instance, null, new[] { typeof(IntPtr), typeof(Desktop) }, null); // 实例化Window对象 var targetWindow = (Window)windowConstructor.Invoke(new object[] { yourWindowHandle, Desktop.Instance });
如果手里是AutomationElement:
var windowConstructor = typeof(Window).GetConstructor( BindingFlags.NonPublic | BindingFlags.Instance, null, new[] { typeof(AutomationElement), typeof(Desktop) }, null); var targetWindow = (Window)windowConstructor.Invoke(new object[] { yourAutomationElement, Desktop.Instance });
方法二:创建Window的子类来访问protected构造
如果你觉得反射不够优雅,可以写一个简单的子类,利用子类能访问父类protected成员的特性:
using TestStack.White; using TestStack.White.UIItems.WindowItems; public class DirectWindow : Window { // 重载构造函数,接收句柄 public DirectWindow(IntPtr handle, Desktop desktop) : base(handle, desktop) { } // 重载构造函数,接收AutomationElement public DirectWindow(AutomationElement element, Desktop desktop) : base(element, desktop) { } }
之后用的时候就很简单了:
// 用句柄实例化 var targetWindow = new DirectWindow(yourWindowHandle, Desktop.Instance); // 或者用AutomationElement实例化 var targetWindow = new DirectWindow(yourAutomationElement, Desktop.Instance);
这两种方法都不需要先查找应用程序,直接用你已有的窗口标识就能拿到Window对象,完美匹配你的需求~
内容的提问来源于stack exchange,提问作者Danhol86
相关产品推荐
相关产品推荐

