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

时间:2011-05-28 09:53:19

标签: delphi menuitem right-click popupmenu

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

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

PopupMenu1.PopupComponent

但是如何找到包含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 个答案:

答案 0 :(得分:9)

我对你的问题感到有些困惑,但既然你排除了其他一切,我只能想象你正在寻找TMenuItem.GetParentMenu

答案 1 :(得分: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;
相关问题