表单上有 TPopupMenu 和三个按钮,分别名为“AddButton”、“EditButton”和“DestroyButton”,并为所有三个按钮添加了 OnClick 事件。窗体的 PopupMenu 属性中的 TPopupMenu。我在 TForm1 类型声明中创建了 PopupMenuItemsClick 过程,以便它可以用作菜单项 OnClick 事件的方法调用。
type
TForm1 = class(TForm)
AddButton: TButton;
EditButton: TButton;
DestroyButton: TButton;
PopupMenu1: TPopupMenu;
procedure AddButtonClick(Sender: TObject);
procedure EditButtonClick(Sender: TObject);
procedure DestroyButtonClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
private
{ Private declarations }
public
procedure PopupMenuItemsClick(Sender: TObject);
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
procedure TForm1.AddButtonClick(Sender: TObject);
var
index: Integer;
NewItem: TMenuItem;
begin
// The owner (PopupMenu1) will clean up this menu item.
NewItem := TMenuItem.Create(PopupMenu1); // Create the new item.
index := PopupMenu1.Items.Count;
PopupMenu1.Items.Add(NewItem);// Add it to the pop-up menu.
NewItem.Caption := 'Menu Item ' + IntToStr(index);
NewItem.Tag := index;
NewItem.OnClick :=
PopupMenuItemsClick; // Assign it an event handler.
end;
procedure TForm1.PopupMenuItemsClick(Sender: TObject);
begin
with Sender as TMenuItem do
begin
case Tag of
0: ShowMessage('first item clicked');
1: ShowMessage('second item clicked');
2: ShowMessage('third item clicked');
3: ShowMessage('fourth item clicked');
end;
end;
end;
{
To edit or destroy an item, grab its pointer
using the Items property.
procedure TForm1.EditButtonClick(Sender: TObject);
var
ItemToEdit: TMenuItem;
begin
ItemToEdit := PopupMenu.Items[1];
ItemToEdit.Caption := 'Changed Caption';
end;
procedure TForm1.DestroyButtonClick(Sender: TObject);
var
ItemToDelete: TMenuItem;
begin
ItemToDelete := PopupMenu.Items[2];
ItemToDelete.Free;
end;
procedure TForm1.FormCreate(Sender: TObject);
var
index: Integer;
NewItem: TMenuItem;
begin
for index := 0 to 3 do
begin
// The owner (PopupMenu1) will clean up this menu item.
NewItem := TMenuItem.Create(PopupMenu1); // Create the new item.
PopupMenu1.Items.Add(NewItem);// Add it to the pop-up menu.
NewItem.Caption := 'Menu Item ' + IntToStr(index);
NewItem.Tag := index;
NewItem.OnClick :=
PopupMenuItemsClick; // Assign it an event handler.
end;
end;
但是当我单击 addmenu 按钮时,没有出现 PopupMenu。任何人都可以找到加载表单或单击任何按钮时没有出现 Popupmenu 的原因。