简体   繁体   中英

Add menu item to .cs files (only) in Visual Studio solution explorer?

I want to add a context menu item to .cs files in solution explorer in VS 2010? I could add it to the project, but not only to .cs files? Any help would be appreciated.

In your OnBeforeQueryStatus Method you need to get the currently selected object and determine the file type, then you can set the Visible property for the MenuCommand .

To enabled OnBeforeQueryStatus you will need to add the following Attribute to your package:

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

Then in your Command Constructor you will need to bind your callback to 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);
...

OnBeforeQueryStatus:

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

GetProjectItem:

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

And with all of that you should be only seeing your button on project files that end with .cs

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM