[英]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? 我想在VS 2010中的解决方案资源管理器中将上下文菜单项添加到.cs文件吗? I could add it to the project, but not only to .cs files?
我可以将其添加到项目中,但不仅可以添加到.cs文件中? 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
. 在
OnBeforeQueryStatus
方法中,您需要获取当前选定的对象并确定文件类型,然后可以为MenuCommand
设置Visible属性。
To enabled OnBeforeQueryStatus
you will need to add the following Attribute to your package: 要启用
OnBeforeQueryStatus
您将需要在包中添加以下属性:
[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
: 然后,在命令构造器中,您需要将回调绑定到
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: 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: 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
所有这些,您应该只会看到以
.cs
结尾的项目文件上的按钮
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.