Holger's Thoughts on Delphi

Friday, November 25, 2005

What component triggered the popup menu?

I hope the headline makes it clear, but I will give additional details first. Let's assume you have one TPopupMenu on your form and two TMemos. Associate both TMemos with the popup menu. When the popup menu pops up, can you tell which one of the two memos was right-clicked?


  • "Yes, it's the Sender-parameter in TPopupMenu.OnPopup." - Wrong.
  • "Of course, it's the Sender-parameter in the OnClick-event of the menu." - Wrong.


I was pretty stunned a couple of days ago as I did not want to implement one popup menu for every component or something scary like that. The solution is easy, if you know it, of course. You just have to look at the right place.

The component that is being right-clicked has a property named "OnContextPopup". So what you could do, use the Tag-property of both TMemos and implement a common OnContextPopup-event for both that sets the Tag of the popup menu accordingly. So you can determine at any time during or after menu popup, which component triggered it.

Easy if you know where to look, but really nasty to find if you look at the menu and its events only.

Happy Thanksgiving everybody!

3 Comments:

  • What about the PopupComponent property? You can read it in the OnPopup to see what was the last TComponent that showed the menu.

    By Anonymous Anonymous, at 11:48 PM  

  • How right you are! I never found it. I have googled for a long time, but could not find it.

    However, "my" solution has the advantage that you can acces the information at any time afterwards. Reading the docs I am really uncertain how long the reference is "valid".

    However, thanks for the "optimization"!

    By Blogger Holger, at 12:11 AM  

  • PopupComponent is valid until it gets set to something else. The only places any VCL component sets PopupComponent are in TControl.WMContextMenu and TToolBar.CheckMenuDropdown. The VCL never sets PopupComponent to nil, so it will continue refering to the last popup-triggering control until another component triggers that same popup menu. It’s really the same technique as your solution.

    By Blogger Rob Kennedy, at 5:31 AM  

Post a Comment

<< Home