在Visual Studio解决方案资源管理器中将菜单项添加到.cs文件(仅限)?

时间:2012-11-04 14:21:08

标签: c# visual-studio-2010 visual-studio-addins

我想在VS 2010的解决方案资源管理器中为.cs文件添加一个上下文菜单项?我可以将它添加到项目中,但不仅仅是.cs文件?任何帮助,将不胜感激。

1 个答案:

答案 0 :(得分:0)

#方法中,您需要获取当前选定的对象并确定文件类型,然后您可以为OnBeforeQueryStatus设置Visible属性。

要启用MenuCommand,您需要将以下属性添加到您的包中:

OnBeforeQueryStatus

然后在命令构造函数中,您需要将回调绑定到[ProvideAutoLoad(Microsoft.VisualStudio.Shell.Interop.UIContextGuids.SolutionExists)] public sealed class YourPackage : Package

BeforeQueryStatus

OnBeforeQueryStatus:

... 
    var commandService = this.ServiceProvider.GetService(typeof(IMenuCommandService)) as OleMenuCommandService;
    if (commandService == null) return;
    var menuCommandId = new CommandID(CommandSet, CommandId);
    var menuItem = new OleMenuCommand(this.MenuItemCallback, menuCommandId);
    menuItem.BeforeQueryStatus +=
        new EventHandler(OnBeforeQueryStatus);
    commandService.AddCommand(menuItem);
...

GetProjectItem:

private void OnBeforeQueryStatus(object sender, EventArgs e)
{
    var myCommand = sender as OleMenuCommand;
    if (null == myCommand) return;
    var selectedObject = Util.GetProjectItem();
    myCommand.Visible = selectedObject.Name.EndsWith(".cs") && this.Enabled;
}

所有这一切你应该只看到以public static ProjectItem GetProjectItem() { IntPtr hierarchyPointer, selectionContainerPointer; Object selectedObject = null; IVsMultiItemSelect multiItemSelect; uint projectItemId; var monitorSelection = (IVsMonitorSelection)Package.GetGlobalService( typeof(SVsShellMonitorSelection)); monitorSelection.GetCurrentSelection(out hierarchyPointer, out projectItemId, out multiItemSelect, out selectionContainerPointer); var selectedHierarchy = Marshal.GetTypedObjectForIUnknown( hierarchyPointer, typeof(IVsHierarchy)) as IVsHierarchy; if (selectedHierarchy != null) { ErrorHandler.ThrowOnFailure(selectedHierarchy.GetProperty( projectItemId, (int)__VSHPROPID.VSHPROPID_ExtObject, out selectedObject)); } return selectedObject as ProjectItem; }

结尾的项目文件上的按钮