2

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

4

1 回答 1

0

在您的OnBeforeQueryStatus方法中,您需要获取当前选择的对象并确定文件类型,然后您可以为MenuCommand.

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

[ProvideAutoLoad(Microsoft.VisualStudio.Shell.Interop.UIContextGuids.SolutionExists)]
public sealed class YourPackage : Package

然后在您的命令构造函数中,您需要将回调绑定到BeforeQueryStatus

... 
    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);
...

OnBeforeQuery 状态:

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;
}

有了所有这些,您应该只在以结尾的项目文件上看到您的按钮.cs

于 2017-01-18T01:43:49.370 回答