delphi - 你如何找出TMenuItem属于哪个TPopupMenu

ros*_*mcm 9 delphi popupmenu right-click menuitem

应该很简单,但我看不到它.

您可以找到右键单击的组件以显示弹出菜单:

PopupMenu1.PopupComponent
Run Code Online (Sandbox Code Playgroud)

但是,如何找到包含TMenuItem的弹出菜单,该菜单依次点击该菜单?

要将问题简化为示例:

我有一系列标签,每个标签都有不同的标题,我有一个弹出菜单,分配给每个标签的PopupMenu属性.

当有人右键单击其中一个标签并打开弹出菜单,然后单击MenuItem1时,我想编码:

procedure TForm1.MenuItem1Click(Sender: TObject);

begin
MsgBox (Format ('The label right-clicked has the caption %', [xxxx.Caption ])) ;
end ;
Run Code Online (Sandbox Code Playgroud)

xxxx应该是什么?

实施答案

感谢两位受访者.我最终得到的是:

procedure TForm1.MenuItem1Click(Sender: TObject);

var
    AParentMenu : TMenu ;
    AComponent  : TComponent ;
    ALabel      : TLabel ;

begin
AParentMenu := TMenuItem (Sender).GetParentMenu ;
AComponent  := TPopupMenu (AParentMenu).PopupComponent ;
ALabel      := TLabel (AComponent) ;
MsgBox (Format ('The label right-clicked has the caption %', [ALabel.Caption ])) ;
end ;
Run Code Online (Sandbox Code Playgroud)

它还会询问涉及哪个TMenuItem,因此给了我一段代码,我可以将其放入其他OnClick处理程序中,而不需要修改.

Dav*_*nan 9

我对你的问题感到有点困惑但是因为你已经排除了其他一切,我只能想象你在寻找TMenuItem.GetParentMenu.


Jar*_*cki 6

procedure TForm1.MenuItem1Click(Sender: TObject);
var pop:TPopupMenu;
    lbl:TLabel;
begin
  // Firstly get parent TPopupMenu (needs casting from TMenu) 
  pop:= TPopupMenu(MenuItem1.GetParentMenu()); 
  // pop.PopupComponent is the "source" control, just cast it to Tlabel
  lbl:= TLabel(pop.PopupComponent);            

  ShowMessage(Format('The label right-clicked has the caption %s',[lbl.Caption]));
end;
Run Code Online (Sandbox Code Playgroud)