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
  1. Drop a TPopupMenu component on the form
  2. Defines some menu items for the TPopupMenu component
  3. Bind the TPopupMenu component to the Form (TForm.PopupMenu)
  4. 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
  1. Right Click on Form show the TPopupMenu component
  2. Right Click on controls show the default popup menu
There are at least 2 ways to achieve that:
  1. Trap the TForm.OnMouseDown event
  2. 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:
procedure TForm1.AfterConstruction;
Self.PopupMenu.AutoPopup := False;

procedure TForm1.FormContextPopup(Sender: TObject; MousePos: TPoint; var
Handled: Boolean);
var C: TControl;
 P: TPoint;
Handled := False;
C := ControlAtPos(MousePos, True, True, True);
if C = nil then begin
 P := ClientToScreen(MousePos);
 Self.PopupMenu.Popup(P.X, P.Y);
 Handled := True;

No comments: