You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

.NET 7 C#程序调用LegacyIAccessiblePattern报错,求正确库引用方法

解决.NET 7中找不到LegacyIAccessiblePattern的问题

问题背景

我在Windows系统中使用.NET 7的C#程序尝试点击某应用内的按钮,通过Windows Inspect.exe查看该按钮仅具备IsLegacyIAccessiblePatternAvailable = true属性。尝试用以下代码调用按钮:

if (button_Create.TryGetCurrentPattern(LegacyIAccessiblePattern.Pattern, out var pattern))
{
  var legacyPattern = (System.Windows.Automation.LegacyIAccessiblePattern)pattern;
  legacyPattern.DoDefaultAction();
}

运行时出现CS0103和CS0234错误,提示找不到LegacyIAccessiblePattern,但System.Windows.Automation下的其他方法均可正常使用。

解决步骤

  • LegacyIAccessiblePattern属于Windows专属的UI自动化旧版API,.NET 7默认未包含相关程序集,需按以下方式引入:
    1. 打开Visual Studio,右键项目选择「管理NuGet程序包」
    2. 在「浏览」标签页搜索Microsoft.Windows.Compatibility,点击安装该包
    3. 确保代码文件顶部已添加命名空间引用:
      using System.Windows.Automation;
      
    4. 重新编译项目,此时LegacyIAccessiblePattern类型即可正常识别

补充说明

若不想安装完整兼容性包,也可单独搜索并安装System.Windows.Automation.UIAutomationClient和System.Windows.Automation.UIAutomationTypes两个NuGet包,同样能解决类型找不到的问题。

内容的提问来源于stack exchange,提问作者Lemonbonbon

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.06 04:22:46