65.9K
CodeProject 正在变化。 阅读更多。
Home

适用于所有 Visual Studio 项目的“全部折叠”插件

starIconstarIconstarIcon
emptyStarIcon
starIcon
emptyStarIcon

3.75/5 (4投票s)

2011年8月4日

CPOL

3分钟阅读

viewsIcon

36844

downloadIcon

768

使用 C# 折叠 Visual Studio IDE 2005、2008 或 2010 中所有打开的项目

引言

当我们打开一个包含大量项目的 Visual Studio 解决方案时,通常所有项目都会处于展开模式。Visual Studio IDE 中没有直接的工具菜单支持折叠所有展开的项目。所以我想创建一个满足此目的的 Visual Studio 插件。四处搜寻之后,我找到了许多支持我提到的功能的宏,但我找不到可以使用来在 .NET 中实现“全部折叠”功能的纯 C# 代码。所以我想用 C# 自己创建一个。

以下是开发此插件的各个步骤。

图 1 - 创建一个 Visual Studio 插件项目

创建 Visual Studio 插件项目后,创建一个扩展自 IDTExtensibility2 IDTCommandTarget 的类。您必须使用的主要对象是 DTE2 和 AddIn。您需要添加引用二进制文件以包含 EnvDTE EnvDTE80

我使用以下两个函数来实现核心的全部折叠功能。

/// <summary>
      /// Command to Collapse All Nodes.
      /// </summary>
      private void DoCollapse()
/// <summary>
      /// To Collapse all the nodes in the tree 
      /// </summary>
      /// <param name="item"></param>
      /// <param name="solutionExplorer"></param>
      private void Collapse(UIHierarchyItem item,ref UIHierarchy solutionExplorer)

DoCollapse 函数是从 IDTCommandTarget 接口的 Exec 函数中调用的。

/// <summary>Implements the Exec method of the IDTCommandTarget interface. 
/// This is called when the command is invoked.</summary>
/// <param term='commandName'>The name of the command to execute.</param>
/// <param term='executeOption'>Describes how the command should be run.</param>
/// <param term='varIn'>Parameters passed from the caller to the command handler.</param>
/// <param term='varOut'>Parameters passed from the command handler to the caller.</param>
/// <param term='handled'>Informs the caller if the command was handled or not.</param>
/// <seealso class='Exec' />
public void Exec(string commandName, vsCommandExecOption executeOption, 
	ref object varIn, ref object varOut, ref bool handled)

将名称添加到您的工具栏菜单

您可以通过更改 AddNamedCommand2 中的参数,在工具栏中添加您自己的名称。在给定的示例中,我将工具栏的名称设置为“CollapseAll_SNK”。

为工具栏菜单添加图标

void OnConnection() 函数中的 commands.AddNamedCommand2() 函数中,我使用了 6743 作为函数 AddNamedCommand2 的第五个参数。您是否注意到了 CollaspeAll_SNK 菜单中的红色星形?6743 是红色星形的索引值。默认索引值为 59,该图标是一个笑脸。要更改为不同的标准图标,请将此索引号更改为 59 6743 之间的范围。

如果您在 Microsoft.VisualStudio.CommandBars 库中找不到合适的图标,您可以使用自定义位图作为插件的命令图标。位图包含在卫星 DLL 中作为资源。有关更多信息,请参阅如何:在插件按钮上显示自定义图标。创建卫星 DLL 资源后,您再将 AddNamedCommand2 指向自定义图标。

图 2 - VS2010 中的“全部折叠”工具菜单

图 3 - VS2008 和 VS2005 中的“全部折叠”工具菜单

关于“全部折叠”插件安装程序

我还为上述创建的插件创建了一个插件安装程序。使用此安装程序,您可以通过选择需要附加插件的 Visual Studio 版本来将“全部折叠”插件安装到您的机器上。安装后,如果您的 Visual Studio 已经打开,您应该关闭它以反映更改。

图 4 - “全部折叠”插件安装程序 UI

包含的二进制文件

  • CollapseAll.dll
  • CollapseAll_SNK.AddIn
  • CollaspeAll_AddinInstaller.exe

结论

希望本文能让您对如何创建 Visual Studio 插件有一个大致的了解,更重要的是获得为您的 Visual Studio 创建的“全部折叠”插件。

参考文献

© . All rights reserved.