UIA:从控件类型名称(字符串)中获取 ControlType [英] UIA: Get ControlType from control type name (string)

查看:21
本文介绍了UIA:从控件类型名称(字符串)中获取 ControlType的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Using Microsoft UI Automation. I have a string which represents UIA control type, like "Window" or "Button". I would like to get a ControlType object which fits this string. How to do it? Is some enumerations exists which represents all the UIA control types? I found only that ControlType has ControlType.LookupById(int) method. But I have to know correspondence between ID and name. Of course, I can create my own switch with all the possible UIA control types, or even use reflection to get all the members of ControlType factory. But I'm sure should be easier way..

推荐答案

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

I've found such way, using PresentationCore.dll, very strange for me, that such enum doesn't exist in standart UIA DLL. Also please pay attention, that there is a bug in ControlType class, I guess due to its private static constructor. If you call ControlType.LookupById(enumId) 1st time, it will return null, but in the 2nd time will be OK. The solution is quite simple -- just call ToString before usage, it will initialize the static constructor :)

    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);

这篇关于UIA:从控件类型名称(字符串)中获取 ControlType的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆