Delphi动态创建菜单
1、打开Delphi7集成开发环境,在默认新建工程里,放置一个Button1按钮和MainMenu1菜单项,设置Button1的Caption属性为添加主菜单。
2、在Button1的ObjectInspector选项卡设置Button1的OnClick响应事件,代码如下:procedure TForm1.Button1Click(Sender: TObject);var files,edit:TMenuItem;begin files:=TMenuItem.Create(self); edit:=TMenuItem.Create(self); files.Caption:='文件'; edit.Caption:='编辑'; Form1.MainMenu1.AutoHotkeys:=mamanual;//指定为手动快捷键; 默认是自动添加的 Form1.MainMenu1.Items.Add(files); Form1.MainMenu1.Items.Add(edit);end;
3、F9运行程序,点击添加主菜单按钮后,可以看到程序多了两个菜单项,分别为文件和编辑
4、关闭程序,在窗体上再放置一个Button2按钮,设置Captain属性:添加菜单项,同样的方法给Button2添加OnClick响应函数,代码如下:procedure TForm1.Button2Click(Sender: TObject);var files,edit,new,copy:TMenuItem;begin files:=TMenuItem.Create(self); edit:=TMenuItem.Create(self); files.Caption:='文件'; edit.Caption:='编辑'; Form1.MainMenu1.AutoHotkeys:=mamanual; Form1.MainMenu1.Items.Add(files); Form1.MainMenu1.Items.Add(edit); new:=TMenuItem.Create(self); copy:=TMenuItem.Create(self); new.Caption:='新建'; copy.Caption:='拷贝'; files.Add(new); edit.Add(copy);end;F9运行程序,可以发现在文件菜单下增加了新建菜单项,在编辑菜单增加了拷贝菜单项
5、在Unit1.pas中为我们添加的菜单项添加响应事件,在Form1类的private中添加方法声明,在imp造婷用痃lement中编写函数具体代码如下: private { Private declarations } procedure test(Sender:TObject); public { Public declarations } end;var Form1: TForm1;implementation{$R *.dfm}procedure TForm1.test(Sender: TObject);begin showmessage('测试动态添加菜单') ;end;同时在上面的Button2的响应方法中添加两行代码,为新建和复制按钮OnClick添加响应方法test(),添加后Button2的OnClick响应方法如下:procedure TForm1.Button2Click(Sender: TObject);var files,edit,new,copy:TMenuItem;begin files:=TMenuItem.Create(self); edit:=TMenuItem.Create(self); files.Caption:='文件'; edit.Caption:='编辑'; Form1.MainMenu1.AutoHotkeys:=mamanual; Form1.MainMenu1.Items.Add(files); Form1.MainMenu1.Items.Add(edit); new:=TMenuItem.Create(self); copy:=TMenuItem.Create(self); new.Caption:='新建'; copy.Caption:='拷贝'; new.OnClick:=test; copy.OnClick:=test; files.Add(new); edit.Add(copy);end;
6、F9运行程序,点击添加菜单项后,再点击文件-新建菜单,会弹出对话框。证明菜单项的响应事件添加成功。