UiAutomationCore.dll 中的 System.AccessViolationException

问题描述

我们有一个测试自动化工具,它大量使用 UI 自动化 API。在最新版本的 Windows(如 Windows 10 21H2、Windows 11)中,api 在调用 AutomationElement 类的方法之一时抛出异常 System.AccessViolationException。 这是我们的代码

AutomationElement uiaElement;
....            
var cr = new CacheRequest
{
    AutomationElementMode = AutomationElementMode.None,TreeScope = TreeScope.Element,TreeFilter = Automation.RawViewCondition
};
cr.Add(InvokePattern.Pattern);
cr.Add(TogglePattern.Pattern);
cr.Add(RangeValuePattern.Pattern);
cr.Add(ValuePattern.Pattern);
cr.Add(ItemContainerPattern.Pattern);
cr.Add(VirtualizedItemPattern.Pattern);

var cachedElement = uiaElement.GetUpdatedCache(capabilitiesCacheRequest);

和堆栈跟踪:

enter image description here

方法 GetUpdatedCache 来自 AutomationElement(UIAutomationClient.dll) 并从 UIAutomationCore.dll 调用方法 RawUiahpatternObjectFromVariant - 此方法抛出异常,我不知道如何鉴于在早期版本的 Windows 上一切正常,请继续。

目前我们只是尝试处理这个异常 - 当然从长远来看这是不可接受的。

需要提及的一点是,我们在其上测试过的两个新版本的 Windows 都处于预览/测试状态。是否有可能某些 API 在此类版本中被“禁用”(当然它们也可能被破坏),有没有人有过这种情况的经验?我在问这两个问题 - 一般解决 System.AccessViolationException 和在测试版/预览版中无法正常工作的 API。

解决方法

您可能需要完全关闭 Windows UAC 和 Defender/SmartScreen,并将 manifest 添加到 exe 以在提升的帐户下运行测试。