How to create a button with drop-down menu?

霸气de小男生 提交于 2019-12-05 06:02:44

I am assuming you mean a button that drops down a menu when clicked.

You can also just manually code your button click to drop down a TPopupMenu under it.

Example: Drop anything with a TClickEvent (maybe a TButton) and a TPopupMenu on your form. Add some menu items. Then add the following OnClick event handler:

procedure TForm86.Button1Click(Sender: TObject);
var
  button: TControl;
  lowerLeft: TPoint;
begin
  if Sender is TControl then
  begin
    button := TControl(Sender);
    lowerLeft := Point(button.Left, button.Top + Button.Height);
    lowerLeft := ClientToScreen(lowerLeft);
    PopupMenu1.Popup(lowerLeft.X, lowerLeft.Y);
  end;
end;

And viola! Just like magic. You could wrap it all up in a component if you plan to reuse it. Maybe even sell it online.

Note: If you want a delay, then extract that code in another method and then set a timer OnClick and turn the timer of OnMouseLeave. Then if the timer fires you can call the extracted method. Not sure how you would do it on a keyboard click. I don't know if Firefox, etc. supports that either.

Jim's answer is great, but didn't quite work for me at first. ClientToScreen uses Form86's method, which is only correct if the button is directly on the form. It should be the button's ClientToScreen method that is called, like this:

procedure TForm86.Button1Click(Sender: TObject);
var
  button: TControl;
  lowerLeft: TPoint;
begin
  if Sender is TControl then
  begin
    button := TControl(Sender);
    lowerLeft := Point(0, button.Height);
    lowerLeft := button.ClientToScreen(lowerLeft);
    PopupMenu1.Popup(lowerLeft.X, lowerLeft.Y);
  end;
end;

This works no matter where the button is.

Sure. Put a toolbar on the page. Right-click on the toolbar, add a button. Set the button's style to tbsDropDown. Put a PopupMenu on the page. Double click on the PopupMenu to define menu items. Then, go back to the button you created and set its DropdownMenu property to point to the PopupMenu you just created.

If you don't want to use a toolbar, the raize (www.raize.com) and express editors (www.DevExpress.com) libraries have components that can do this.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!