Delphi - 如何找出一个 TMenuItem 属于哪个 TPopupMenu

11

应该很简单,但我不知道怎么做。

你可以通过以下方式找出被右键单击以显示弹出菜单的组件:

PopupMenu1.PopupComponent

但是你如何找到包含TMenuItem的弹出菜单,而TMenuItem又是在哪个菜单中被点击的呢?

为了简化问题,举个例子:

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

当有人右键单击其中一个标签并弹出弹出菜单,然后点击MenuItem1时,我想编写以下代码:

procedure TForm1.MenuItem1Click(Sender: TObject);

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

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 ;

它还会查询哪个TMenuItem参与其中,因此给我一个代码片段,可以在其他OnClick处理程序中使用,而无需进行大量修改。

2个回答

10

我有点困惑你的问题,但既然你排除了其他所有可能性,我只能想象你在寻找TMenuItem.GetParentMenu


我知道这会很简单... 我一直在查看TMenuItem的属性,从来没有想过要查看它的方法。非常感谢。 - rossmcm

9
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;

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接