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

Visual Studio 设计器中的全局 MenuCommand Verb

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.33/5 (4投票s)

2008年9月7日

CPOL

2分钟阅读

viewsIcon

20465

downloadIcon

209

介绍一种将全局上下文菜单命令添加到 Visual Studio 设计器的技巧。

ContextMenuCommand

引言

许多 .Net 组件供应商需要将全局上下文菜单命令添加到 Visual Studio,该命令应在任何需要的 DesignerHost(Windows 窗体、Web 窗体、用户控件等)及其对应的窗体处于活动状态时可用。 然而,.Net 框架没有提供任何永久添加全局上下文菜单命令的方法。
它有 IMenuCommandService,其 AddVerb() 方法声称可以添加全局 verb。 但实际上,它特定于使用 IMenuCommandService 的组件。 只要控件的选择更改为其他内容,verb 就会丢失。 我开发了一个 hack 来将此功能完美地引入 .Net 框架。

背景

当我开发我的 Windows 窗体布局管理器 'SmartLayouts' 时,我正好有这个需求。 我需要它,因为我需要为我的用户提供易于使用的布局任务。 工具栏按钮、菜单命令可以做到,但从长远来看,这对于用户来说看起来很麻烦。 经过几天的深入研究,我发现了创建全局 verb 的技巧,该 verb 保留在所需 DesignerHost 的上下文菜单中。
由于全局级别的命令必须是与 Visual Studio 启动一起激活的 Visual Studio 插件,因此我的解决方案也是一个 Visual Studio 插件。

方法

为了添加 Verb,您首先需要确保加载了正确的 DesignerHost。 这可以通过将 IDesignerHost.RootComponentSystem.Windows.Forms.Form 进行比较来确保(您可以根据您的需求使用其他内容)。 之后,我们从 GetService 方法获取 ISelectionService

ISelectionService sel = host.RootComponent.Site.GetService(typeof(ISelectionService)) as ISelectionService;


我们将一个 EventHandler 附加到 ISelectionService.SelectionChanged。 该事件处理程序是这个 hack 的核心。 只要选择发生变化,事件处理程序就会执行,将所需的 verb 重新添加到 IMenuCommandService verb 列表中。 事件处理程序包含类似于以下的代码。

IMenuCommandService mcs = host.RootComponent.Site.GetService(typeof(IMenuCommandService)) as IMenuCommandService;
if (!mcs.Verbs.Contains(verb)) 
{  
      mcs.Verbs.Add(verb);
} 


现在,结果是只要选择更改为任何其他组件的设计器,您就可以获得所需的 Verb。 总之,每当您右键单击时,您都会在上下文菜单中看到所需的命令!

源代码

给出了示例项目的源代码。 但是,您需要在您的 addin 文件夹(通常在 My Documents\Visual Studio 2005\Addins 中)中添加 ContextMenuCommand.Addin 并编辑其 xml 节点 <assembly> 以指向实际的 ContextMenuCommand.dll。
<Assembly>C:\Documents and Settings\vkhaitan\My Documents\Visual Studio 2005\Projects\ContextMenuCommand\ContextMenuCommand\bin\ContextMenuCommand.dll</Assembly>
所有文档和源代码均提供 The Code Project Open License (CPOL) 许可证。

结论

如果 .Net 框架为此提供了方法,而我们不需要求助于这些 hack,那就更好了。 但是,在实践中,我发现这个 hack 运行良好,并且从未向我展示过任何问题或错误。 因此,您可以在需要时使用它。

© . All rights reserved.