本帖最后由 lies2014 于 2024-10-10 11:53 编辑
这种用递归实现比较简单,逻辑也清晰,不管多少层菜单,一个函数搞定
[Delphi] 纯文本查看 复制代码 unit Unit1;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants,
System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.Menus;
type
{ TForm1 }
TForm1 = class(TForm)
AAA1: TMenuItem;
BBB1: TMenuItem;
N7771: TMenuItem;
N8881: TMenuItem;
N5: TMenuItem;
N4: TMenuItem;
N2221: TMenuItem;
N1111: TMenuItem;
N3: TMenuItem;
N2: TMenuItem;
N1: TMenuItem;
PopupMenu1: TPopupMenu;
procedure FormCreate(Sender: TObject);
private
procedure MainMenu1Click(Sender: TObject);
procedure SetItem(tmpItems: TMenuItem);
public
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
{ TForm1 }
procedure TForm1.MainMenu1Click(Sender: TObject);
var
MenuItem: TMenuItem;
begin
if Sender is TMenuItem then //确保Sender是TMenuItem类型
begin
MenuItem := TMenuItem(Sender); //获取并显示菜单项的Caption
ShowMessage(MenuItem.Caption);
end;
end;
procedure TForm1.SetItem(tmpItems: TMenuItem);
var
i: Integer;
begin
for i := 0 to tmpItems.Count - 1 do
begin
if tmpItems[i].Count = 0 then tmpItems[i].OnClick := MainMenu1Click
else SetItem(tmpItems[i]);
end;
end;
procedure TForm1.FormCreate(Sender: TObject);
begin
SetItem(PopupMenu1.Items);
end;
end. |