在 DesignSurface 设计器界面中如果想要显示右键菜单,那么 DesignSurface 必须添加 MenuCommandService
下面提供一个类来实现这个功能 其中 类 MenuCommandService 继承于 System.ComponentModel.Design.MenuCommandService
并对 ShowContextMenu 方法进行重写。
1 class MenuCommandService : System.ComponentModel.Design.MenuCommandService 2 { 3 Control panel; 4 5 public MenuCommandService(Control panel, IServiceProvider serviceProvider) : base(serviceProvider) { 6 this.panel = panel; 7 } 8 9 public override void ShowContextMenu(CommandID menuID, int x, int y) { 10 11 var selectionService = (ISelectionService)base.GetService(typeof(ISelectionService)); 12 13 if (selectionService != null) { 14 Console.WriteLine(menuID); 15 16 ContextMenuStrip contextMenu = AddMenuCommandServiceContextMenuStrip(); 17 Point p = panel.PointToClient(new Point(x, y)); 18 contextMenu.Show(panel, p); 19 } 20 } 21 22 23 // private Method 24 private ContextMenuStrip AddMenuCommandServiceContextMenuStrip() { 25 ContextMenuStrip contextMenu = new ContextMenuStrip(); 26 ToolStripMenuItem cutMenuItem = new ToolStripMenuItem("剪切(T)"); //Ctrl+X 27 cutMenuItem.Click += (s, e) => { 28 this.GlobalInvoke(StandardCommands.Cut); 29 }; 30 cutMenuItem.Enabled = EnableCommand(StandardCommands.Cut); 31 contextMenu.Items.Add(cutMenuItem); 32 33 ToolStripMenuItem copyMenuItem = new ToolStripMenuItem("复制(Y)"); //Ctrl+C 34 copyMenuItem.Click += (s, e) => { 35 this.GlobalInvoke(StandardCommands.Copy); 36 }; 37 copyMenuItem.Enabled = EnableCommand(StandardCommands.Copy); 38 contextMenu.Items.Add(copyMenuItem); 39 40 41 ToolStripMenuItem pasteMenuItem = new ToolStripMenuItem("粘贴(P)"); // Ctrl+V 42 pasteMenuItem.Click += (s, e) => { 43 this.GlobalInvoke(StandardCommands.Paste); 44 }; 45 pasteMenuItem.Enabled = EnableCommand(StandardCommands.Paste); 46 contextMenu.Items.Add(pasteMenuItem); 47 48 ToolStripMenuItem deleteMenuItem = new ToolStripMenuItem("删除(D)");//Del 49 deleteMenuItem.Click += (s, e) => { 50 this.GlobalInvoke(StandardCommands.Delete); 51 }; 52 deleteMenuItem.Enabled = EnableCommand(StandardCommands.Delete); 53 contextMenu.Items.Add(deleteMenuItem); 54 55 return contextMenu; 56 } 57 58 private bool EnableCommand(CommandID menuID) { 59 MenuCommand menuCommand = FindCommand(menuID); 60 if (menuCommand == null) 61 return false; 62 return menuCommand.Enabled; 63 } 64 }
那么就可以通过右键 菜单的方式 实现 对控件或控件集 进行 复制,粘贴,剪切,删除的功能了,
需要注意的是,这里使用 了 EnableCommand 方法 来对 右键菜单子项进行可用性判断。