2

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.

Rashmi Pandit
  • 23,230
  • 17
  • 71
  • 111
KasunLak
  • 51
  • 7
  • 2
    This question may help you http://stackoverflow.com/questions/3017063/visual-studio-2010-plug-in-adding-a-context-menu-to-the-solution-explorer – Ramesh Nov 04 '12 at 14:32

1 Answers1

0

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

FiringSquadWitness
  • 666
  • 1
  • 10
  • 27