使用UI自动化框架公开自定义属性 [英] Exposing custom properties using UI Automation Framework
问题描述
使用System.Windows.Automation给出一个非常基本的 WinForms 自定义/用户控件,就可以操纵该自定义控件的内置属性.
Given a very basic WinForms custom/user control, using System.Windows.Automation it is possible to manipulate built in properties for the custom control.
这是这样完成的:
public object GetPropertyValue(int propertyId)
{
if (propertyId == AutomationElementIdentifiers.NameProperty.Id)
{
return "Hello World!";
}
}
我想做的是向ui自动化公开自定义属性,例如ReadyState,LastAccessed等.
What I would like to do is expose custom properties to ui automation such as ReadyState, LastAccessed, Etc.
这可能吗?
推荐答案
不,您不能扩展属性列表,并且由于使用了UI自动化支持不佳的Winforms(使用IAccessible)而使情况变得复杂与桥梁等).
No, you can't extend the list of properties, and this is complicated by the fact you use Winforms that has a poor UI Automation support (it uses IAccessible with bridges etc.).
但是您可以做的是在自动化树中添加一些伪造的对象,例如,下面是一个示例Winforms UserControl:
What you can do though is add some fake objects to the automation tree, for example, here is a sample Winforms UserControl that does it:
public partial class UserControl1 : UserControl
{
public UserControl1()
{
InitializeComponent();
Button button = new Button();
button.Location = new Point(32, 28);
button.Size = new Size(75, 23);
button.Text = "MyButton";
Controls.Add(button);
Label label = new Label();
label.Location = new Point(49, 80);
label.Size = new Size(35, 13);
label.Text = "MyLabel";
Controls.Add(label);
MyCustomProp = "MyCustomValue";
}
public string MyCustomProp { get; set; }
protected override AccessibleObject CreateAccessibilityInstance()
{
return new UserControl1AccessibleObject(this);
}
protected class UserControl1AccessibleObject : ControlAccessibleObject
{
public UserControl1AccessibleObject(UserControl1 ownerControl)
: base(ownerControl)
{
}
public new UserControl1 Owner
{
get
{
return (UserControl1)base.Owner;
}
}
public override int GetChildCount()
{
return 1;
}
public override AccessibleObject GetChild(int index)
{
if (index == 0)
return new ValueAccessibleObject("MyCustomProp", Owner.MyCustomProp);
return base.GetChild(index);
}
}
}
public class ValueAccessibleObject : AccessibleObject
{
private string _name;
private string _value;
public ValueAccessibleObject(string name, string value)
{
_name = name;
_value = value;
}
public override AccessibleRole Role
{
get
{
return AccessibleRole.Text; // activate Value pattern
}
}
// note you need to override with member values, base value cannot always store something
public override string Value { get { return _value; } set { _value = value; } }
public override string Name { get { return _name; } }
}
这是它在自动化树中的显示方式(使用inspect.exe工具):
And this is how it appears in the automation tree (using the inspect.exe tool):
请注意,此技术还支持写回属性,因为它基于ValuePattern.
Note this technique also supports writing back to the property because it's based on the ValuePattern.
这篇关于使用UI自动化框架公开自定义属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!