Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

delphi - how do you find out which TPopupMenu a TMenuItem belongs to

Should be simple enough but I can't see it.

You can find out the component that was right-clicked on to display a popup menu with:

PopupMenu1.PopupComponent

but how do you find out the popup menu that contains the TMenuItem that was in turn clicked on that menu?

To simplify the problem to an example:

I have a series of labels, each with a different caption, and I have a popup menu that is assigned to the PopupMenu property of each of the labels.

When someone right-clicks one of the labels and brings up the popup menu, and then clicks on MenuItem1, I want to code:

procedure TForm1.MenuItem1Click(Sender: TObject);

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

What should xxxx be?

Implemented Answer

Thanks to both respondents. What I ended up with was this:

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 ;

which also interrogates which TMenuItem was involved and therefore gives me a fragment of code I can drop into other OnClick handlers with less modification.

like image 764
rossmcm Avatar asked May 28 '11 09:05

rossmcm


2 Answers

I'm a little confused by your question but since you've ruled out everything else I can only imagine you are looking for TMenuItem.GetParentMenu.

like image 160
David Heffernan Avatar answered Oct 05 '22 21:10

David Heffernan


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;
like image 31
Jarek Bielicki Avatar answered Oct 05 '22 20:10

Jarek Bielicki