您不需要任何Nuget,只需将Windows中的UIAutomationClient COM DLL作为COM对象引用即可:
现在,要创建真实的条件,如您所说,您必须使用在...上实现的IUIAutomation::CreateTrueCondition method.CUIAutomation8(根类,它实现了IUIAutomation
).我已经编写了一些扩展方法来简化这一过程:
using System;
using System.Collections.Generic;
using System.Linq;
using UIAutomationClient;
internal class Program
{
static void Main()
{
Console.WriteLine("Starting...");
var desktop = UIAUtilities.Automation.GetRootElement();
Console.WriteLine("Destop name is {0}", desktop.CurrentName);
foreach (var element in desktop.EnumerateAll(TreeScope.TreeScope_Children))
{
Console.WriteLine(element.CurrentName);
}
Console.WriteLine("Ending...");
}
}
public static class UIAUtilities
{
private static readonly Lazy<CUIAutomation8> _automation = new(() => new CUIAutomation8());
public static CUIAutomation8 Automation => _automation.Value;
public static IEnumerable<IUIAutomationElement> EnumerateAll(this IUIAutomationElement element, TreeScope scope = TreeScope.TreeScope_Children, IUIAutomationCondition condition = null)
{
if (element == null)
return Enumerable.Empty<IUIAutomationElement>();
condition ??= Automation.CreateTrueCondition();
return ForEach(element.FindAll(scope, condition));
}
public static IEnumerable<IUIAutomationElement> ForEach(this IUIAutomationElementArray array)
{
if (array == null)
yield break;
for (var i = 0; i < array.Length; i++)
{
var element = array.GetElement(i);
if (element != null)
yield return element;
}
}
}
下面是带有COM引用的项目文件(.NET core+)应该是什么样子:
<Project Sdk="Microsoft.NET.Sdk">
...
<ItemGroup>
<COMReference Include="UIAutomationClient">
<WrapperTool>tlbimp</WrapperTool>
<VersionMinor>0</VersionMinor>
<VersionMajor>1</VersionMajor>
<Guid>944de083-8fb8-45cf-bcb7-c477acb2f897</Guid>
<Lcid>0</Lcid>
<Isolated>false</Isolated>
<EmbedInteropTypes>true</EmbedInteropTypes>
</COMReference>
</ItemGroup>
...
</Project>