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