打开主窗体代码界面,为Form1添加一个私有变量:
private MenuCommandService menuCommandService;
修改Load事件代码,代码如下:
DesignSurface surface = new DesignSurface(); //设计器
toolBoxService = new DemoToolboxService();
toolBoxService.ToolBox = new ListBox();
toolBoxService.ToolBox.Items.Add("Point");
toolBoxService.ToolBox.Items.Add(new ToolboxItem(typeof(Button)));
toolBoxService.ToolBox.Items.Add(new ToolboxItem(typeof(TextBox)));
toolBoxService.ToolBox.Items.Add(new ToolboxItem(typeof(Label)));
toolBoxService.ToolBox.Items.Add(new ToolboxItem(typeof(TabControl)));
toolBoxService.ToolBox.Items.Add(new ToolboxItem(typeof(StatusBar)));
toolBoxService.ToolBox.Dock = DockStyle.Fill;
this.panel1.Controls.Add(toolBoxService.ToolBox);
IServiceContainer container = surface.GetService(typeof(IServiceContainer)) as IServiceContainer;
menuCommandService = new MenuCommandService(surface);
if (container != null)
{
container.AddService(typeof(IToolboxService), toolBoxService);
container.AddService(typeof(IMenuCommandService), menuCommandService);
}
surface.BeginLoad(typeof(Form));
Control view = (Control)surface.View;
view.Dock = DockStyle.Fill;
//this.Controls.Add(view);
this.panel2.Controls.Add(view);
this.propertyGrid1.SelectedObject = surface.ComponentContainer.Components[0];
selectionService = surface.GetService(typeof(ISelectionService)) as ISelectionService;
selectionService.SelectionChanged += new EventHandler(selectionService_SelectionChanged);
我们以删除功能来做测试,在主窗体的设计界面上添加一个MenuStrip,在MenuStrip上添加Edit菜单项,在Edit菜单项下添加子菜单Delete,设置其快捷键为Del(ShowcutKeys属性),为Delete菜单项写事件代码:
private void deleteToolStripMenuItem_Click(object sender, EventArgs e)
{
menuCommandService.GlobalInvoke(StandardCommands.Delete);
}
运行方案,在设计器上添加几个控件,然后在选中一个或几个控件,按下Del键或者点击菜单Edit->Delete,所选的控件就会被删除。
其他的菜单命令如全选,如对齐等等,皆可如此实现。StandardCommands包含的命令实在太多了。
现在除了序列化资源,生成代码,事件处理这三项功能没有实现外,其他的都已经完成。