前言:
最近一直在做RPA相关的项目,里面有一个核心就是UI自动化,在开发的过程中,一方面叹服于这种非侵入式的软件操作,一方面又在思考,作为软件开发者,我们自己又该如何像sap应用程序一样,可以自己开启或者关闭UI自动化。
WPF是如何实现控件的UI自动化:
WPF控件和winform控件不一样,是完全画出来的,没有单独的句柄,WPF控件通过派生自 AutomationPeer 的对等类的树来支持 UI 自动化。派生自 UIElement 和 ContentElement 的所有类都包含受保护的虚方法 OnCreateAutomationPeer。WPF 调用 OnCreateAutomationPeer 以获取每个控件的自动化对等类对象。自动化代码可以使用对等类来获得关于每个控件的特性和功能的信息,并可以使用对等类来模拟交互使用(WPF 自定义控件的 UI 自动化 | Microsoft Docs)。
如何控制WPF的UI自动化:
了解到WPF是如何实现控件UI自动化的,我们通过定位找到基类UIElement里面的OnCreateAutomationPeer方法,基本上可以了解到以下方法就是生成自动化对等类对象的具体实现:
internal AutomationPeer CreateAutomationPeer()
{
VerifyAccess();
AutomationPeer automationPeer = null;
if (HasAutomationPeer)
{
automationPeer = AutomationPeerField.GetValue(this);
}
else
{
if (!AccessibilitySwitches.get_ItemsControlDoesNotSupportAutomation())
{
AutomationNotSupportedByDefaultField.ClearValue(this);
automationPeer = OnCreateAutomationPeer();
if (automationPeer == null && !AutomationNotSupportedByDefaultField.GetValue(this))
{
automationPeer = OnCreateAutomationPeerInternal();
}
}
else
{
automationPeer = OnCreateAutomationPeer();
}
if (automationPeer != null)
{
AutomationPeerField.SetValue(this, automationPeer);
HasAutomationPeer = true;
}
}
return automationPeer;
}
根据以上源码逻辑展示的结果,我们只需要控制该方法每次获取到的AutomationPeer为空,则可屏蔽WPF应用程序的自动化,正常返回,则可以开启UI自动化。
如何使用:
安装对应Nuget包
Install-Package AutomationAssists -Version 1.1.0
设置窗体测试程序
<Window x:Class="WPFDemo.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:WPFDemo"
xmlns:lan="https://schemas.lan.com/assists/automation"
mc:Ignorable="d" lan:Assists.CanAutomationed="{Binding ElementName=checkBox,Path=IsChecked}"
Title="MainWindow" Height="450" Width="800">
<StackPanel >
<CheckBox Width="150" Height="30" Content="是否打开自动化" x:Name="checkBox"></CheckBox>
<Button Content="这是一个按钮"></Button>
<CheckBox Content="这是一个单选框"></CheckBox>
<TextBox Text="这是一个文本输入框"></TextBox>
</StackPanel>
</Window>