January 2002

Open a Pop-up Menu from any OnClick Event

Steve Zimmelman

The TPopupMenu and the controls that allow the right-click to open it are fine for most uses. But if you're like I am, every now and then you want a pop-up menu to open on the Click event of a button or some other control.

Using this small method, OpenPopup, you can open any pop-up menu from virtually any OnClick event for any control in your application.

Just place code similar to this in the Click event method.



procedure TForm1.Button1Click(Sender: TObject);
begin
  OpenPopup(Sender,PopupMenu1);
end;



Procedure OpenPopup(Const TheControl:TControl;
                    Const PopMnu:TPopupMenu;
                    Const MenuTop:Integer=1;
                    Const xOffSet:Integer=0);
                    
(*******************************************************************
   MenuTop = 0 : Start menu at the Top of the control.
   MenuTop = 1 : Start menu at the bottom of the control.
   xOffSet : Controls the left coordinate (x) position of the menu.
********************************************************************)

var
  p : TPoint ;

Begin
   If (TheControl=Nil) Then Begin
      GetCursorPos(p);
   End Else Begin
      p := TheControl.ClientOrigin ;
      If MenuTop=1 Then
         p.y := p.y + TheControl.Height ;
   End;
   PopMnu.Popup(p.x + xOffSet, p.y);
End;