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

rossmcm picture rossmcm · May 28, 2011 · Viewed 10.1k times · Source

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.

Answer

David Heffernan picture David Heffernan · May 28, 2011

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.