Server-Side UI Automation Provider - WPF Sample
2014-09-14
引用程序集
- UIAutomationProviders.dll
- UIAutomationTypes.dll
- WindowsBase.dll
自动化对等类[1]
WPF 控件通过派生自 AutomationPeer 的对等类的树来支持 UI 自动化。 按照约定,对等类的名称须以控件类的名称开头,并以“AutomationPeer”结尾。 例如,ButtonAutomationPeer 是 Button 控件类的对等类。 这些对等类基本等效于 UI 自动化控件类型,但专用于 WPF 元素。 通过 UI 自动化接口访问 WPF 应用程序的自动化代码不直接使用自动化对等类,但同一进程空间中的自动化代码可以直接使用自动化对等类。
图1 ButtonAutomationPeer metadata
WPF Sample[2]
示例代码如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Windows.Automation.Peers;
using System.Windows.Automation.Provider;
namespace WpfServerProvider
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
UIAButton btn = new UIAButton();
btn.Content = "TestButton";
this.Content = btn;
}
}
//My WPF button class, derive from WPF Button class
public class UIAButton : Button
{
//Override this function to return my derived AutomationPeer class
protected override AutomationPeer OnCreateAutomationPeer()
{
return new UIAButtonAutomationPeer(this);
}
}
//My AutomationPeer class
//Add implementation of UI ValuePattern comparing with base implementation
public class UIAButtonAutomationPeer : ButtonAutomationPeer, IValueProvider
{
//owner parameter is the WPF Button instance
public UIAButtonAutomationPeer(Button owner)
: base(owner)
{
}
//Return UIA Name property
protected override string GetNameCore()
{
string originalName = base.GetNameCore();
return string.Format("{0} {1}", originalName, DateTime.Now.ToLongTimeString());
}
//Return ValuePattern interface
public override object GetPattern(PatternInterface patternInterface)
{
if (patternInterface == PatternInterface.Value)
{
return this;
}
return null;
}
public bool IsReadOnly { get { return true; } }
//ValuePattern's implementation
public string Value
{
get
{
return string.Format("Height={0},Wideth={1}",
Owner.RenderSize.Height, Owner.RenderSize.Width);
}
}
public void SetValue(string value) { }
}
}
图2 UISpy to WPF provider sample