Tuesday, September 11, 2007

Using TPopupMenu control in Delphi

Imagine a form that has several controls. If we right click on the control especially controls like TEdit or TMemo, a default popup menu will shown on screen with common clipboard operations like cut, copy, paste and etc.
However, if we

Drop a TPopupMenu component on the form

Defines some menu items for the TPopupMenu component

Bind the TPopupMenu component to the Form (TForm.PopupMenu)

Compile and Run the application

Right click on any controls on the form will always show the PopupMenu we defined. The default popup menu will no longer shown.
What if we want

Right Click on Form show the TPopupMenu component

Right Click on controls show the default popup menu

There are at least 2 ways to achieve that:

Trap the TForm.OnMouseDown event

Trap the TForm.OnContextPopup event

Both ways have similar coding but the second way is preferable and more complete. The OnMouseDown event will only trigger when we right click the mouse. However, right click is not the only way to fire the popup menu. We may use keyboard to trigger as well.
Here is the coding for OnContextPopup event handler: