UIA:从控件类型名称(字符串)获取ControlType

2024-01-25

使用 Microsoft UI 自动化。我有一个代表 UIA 控件类型的字符串,例如“Window”或“Button”。我想获得一个适合该字符串的 ControlType 对象。怎么做?是否存在一些代表所有 UIA 控件类型的枚举?我只发现 ControlType 有 ControlType.LookupById(int) 方法。但我必须知道ID和名字之间的对应关系。当然,我可以使用所有可能的 UIA 控件类型创建自己的开关,甚至使用反射来获取 ControlType 工厂的所有成员。但我确信应该是更简单的方法..


我发现这样的方式,使用PresentationCore.dll,对我来说非常奇怪,这样的枚举在标准UIA DLL中不存在。另请注意,ControlType 类中有一个错误,我猜是由于其私有的static构造函数。如果你第一次调用 ControlType.LookupById(enumId) ,它将返回 null,但第二次就可以了。解决方案非常简单——只需在使用前调用 ToString 即可,它会初始化静态构造函数:)

    using System.Windows.Automation.Peers;

    // solving the bug with static constructor of ControlType..
    ControlType.Button.ToString();
    string controlTypeString = "Window";
    AutomationControlType typeEnum;
    bool result = Enum.TryParse(controlTypeString, true, out typeEnum);
    if (result) typeEnum = (AutomationControlType)Enum.Parse(typeof(AutomationControlType), controlTypeString);
    int enumId = (int)typeEnum + 50000;
    ControlType controlType = ControlType.LookupById(enumId);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

UIA:从控件类型名称(字符串)获取ControlType 的相关文章

随机推荐