11

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.

rossmcm
  • 5,493
  • 10
  • 55
  • 118

2 Answers2

10

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.

David Heffernan
  • 601,492
  • 42
  • 1,072
  • 1,490
  • I knew it would be simple... I was looking under the properties of TMenuItem and never thought to look at the methods. Many thanks. – rossmcm May 28 '11 at 10:27
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;
Johan
  • 74,508
  • 24
  • 191
  • 319
Jarek Bielicki
  • 856
  • 6
  • 16