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

如何获取Visual Studio错误窗口中选中项的所有属性(含错误码)

从Visual Studio错误窗口获取选中项完整数据(含错误码)

我需要从Visual Studio的错误窗口中获取选中项的完整数据,目前用的方法能拿到选中错误的描述、行号和文档信息,但无法获取错误码(比如CS1002)。另外我试过一段代码,能获取更多字段但同样没有错误码,而且返回的是错误列表里的所有项,不是选中的:

EnvDTE80.DTE2 dte = (EnvDTE80.DTE2)Package.GetGlobalService(typeof(SDTE));
Assumes.Present(dte);
ErrorList errorList = dte.ToolWindows.ErrorList;
for (int i = 1; i <= errorList.ErrorItems.Count; i++)
{
    var itm = (ErrorItem)errorList.ErrorItems.Item(i);
    MessageBox.Show(itm.Description);
}

解决方案:获取选中项的错误码及完整信息

要拿到错误码并仅针对选中项,需要使用Visual Studio SDK的底层接口(IVsTaskList、IVsErrorItem),具体步骤如下:

  1. 确保项目引用Microsoft.VisualStudio.Shell.Interop、Microsoft.VisualStudio.Shell.Interop.11.0等相关程序集。
  2. 使用以下代码实现需求:
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.Shell.Interop;

// 获取IVsTaskList服务实例
IVsTaskList taskList = (IVsTaskList)Package.GetGlobalService(typeof(SVsTaskList));
if (taskList == null) return;

// 获取当前选中的任务项
IVsTaskItem[] selectedItems = new IVsTaskItem[1];
uint selectedCount = 0;
taskList.GetSelectedItems(selectedItems, ref selectedCount);

for (uint i = 0; i < selectedCount; i++)
{
    // 将选中项转换为IVsErrorItem以获取错误码
    if (selectedItems[i] is IVsErrorItem errorItem)
    {
        string errorCode = string.Empty;
        errorItem.GetErrorInfo(out _, out _, out errorCode, out _, out _, out _);
        
        // 同时获取其他基础信息
        string description = string.Empty;
        selectedItems[i].get_Text(out description);
        
        string documentPath = string.Empty;
        selectedItems[i].get_Document(out documentPath);
        
        int lineNumber = 0;
        selectedItems[i].get_Line(out lineNumber);
        
        MessageBox.Show($"错误码:{errorCode}\n描述:{description}\n文件:{documentPath}\n行号:{lineNumber}");
    }
}

关键说明

  • IVsErrorItem的GetErrorInfo方法是获取错误码的核心,这是EnvDTE层的ErrorItem未暴露的字段。
  • GetSelectedItems方法仅返回当前选中的项,解决了原代码返回所有错误项的问题。
  • 该代码适用于Visual Studio扩展项目,需确保服务实例获取逻辑正确。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 22:06:34