Delphi动态添加菜单

unit Unit1;

interface

uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, Menus, StdCtrls, ComCtrls;

type
TMainForm = class(TForm)
MainMenu1: TMainMenu;
Button1: TButton;
N0000000001: TMenuItem;
RichEdit1: TRichEdit;
procedure FormCreate(Sender: TObject);
procedure Button1Click(Sender: TObject);
procedure N0000000001Click(Sender: TObject);
private
procedure MyClick(Sender: TObject);
{ Private declarations }
public
{ Public declarations }
end;

var
MainForm: TMainForm;
subItemName:String;

implementation

{$R *.dfm}

procedure TMainForm.FormCreate(Sender: TObject);
var addSubItem:TMenuItem;
i:Integer;
N:Integer;
SubMenuItemSource:String;
begin
N:=5;
SubMenuItemSource:='动态-';
for i:=0 to N do //N等于要添加动态菜单数目,需事先定义为数值型变量,并赋值
begin
addSubItem:= TMenuItem.Create(Self);
addSubItem.Name := 'A'+IntToStr(i);
addSubItem.Caption := SubMenuItemSource+IntToStr(i);// 步骤1的SubMenuItemSource应先赋值
//FileOpenItem.Add(addSubItem);//在名称为FileOpenItem的菜单项下添加子菜单
addSubItem.OnClick:=self.MyClick;//步骤2的MyClick(),自定义菜单要响应的事件
self.MainMenu1.Items.Add(addSubItem);
end
end;

procedure TMainForm.MyClick(Sender: TObject); //动态菜单OnClick事件响应
begin
ShowMessage(TMenuItem(Sender).Caption); //显示选中的动态菜单标题,
end;

procedure TMainForm.Button1Click(Sender: TObject);
var addSubItem:TMenuItem;
i:Integer;
N:Integer;
SubMenuItemSource:String;
begin
self.MainMenu1.Items[0].OnClick:=nil; //变为无事件
N:=5;
SubMenuItemSource:='KKKKK-';
subItemName:=subItemName+'T';
for i:=0 to N do //N等于要添加动态菜单数目,需事先定义为数值型变量,并赋值
begin
addSubItem:= TMenuItem.Create(Self);
addSubItem.Name := subItemName+IntToStr(i);
addSubItem.Caption := SubMenuItemSource+IntToStr(i);// 步骤1的SubMenuItemSource应先赋值
//FileOpenItem.Add(addSubItem);//在名称为FileOpenItem的菜单项下添加子菜单
addSubItem.OnClick:=self.MyClick;//步骤2的MyClick(),自定义菜单要响应的事件
self.MainMenu1.Items[0].Add(addSubItem);
end
end;


procedure TMainForm.N0000000001Click(Sender: TObject);
begin
showmessage('aaa');
end;

end.

posted on 2017-08-31 02:46  癫狂编程  阅读(1609)  评论(0编辑  收藏  举报

导航

好的代码像粥一样,都是用时间熬出来的