Creating a menu button in Windows

2019-03-15 21:42发布

问题:

Microsoft's User Experience Interaction Guidelines give some UI guidelines for when to use a menu button:

http://i.msdn.microsoft.com/Aa511453.command51(en-us,MSDN.10).png

How do I create one of these menu buttons? I've found information on

  • how to create a split button in Vista and above
  • how to create a toolbar button with a dropdown menu
  • how to create a regular pushbutton and manually wire up an OnClick event handler that pops up a menu

But is there any standard way to create a button, not in a toolbar, with the little down triangle, that automatically pops up a menu when clicked?

(I'm using Delphi / C++Builder, but other solutions are welcome.)

回答1:

You can use the OnClick to force the popup, and for consistency don't use the cursor position, but rather the control position.

procedure TForm1.Button1Click(Sender: TObject);
var
  pt : TPoint;
begin
  Pt.X := Button1.Left;
  Pt.Y := Button1.Top+Button1.Height;
  pt := ClientToScreen(Pt);
  PopupMenu1.Popup(pt.x,pt.y);
end;

You can then add the "glyph" using either a Delphi 2010 button, or a previous version TBitBtn and assign the bitmap/glyph property to an appropriate image and align right.



回答2:

You don't mention which version of Delphi you are using, but in Delphi 2010 TButton has new properties for this: DropDownList which can be associated with a TPopupMenu to define the menu items, and Style which can be set to bsSplitButton.

This produces a button that you can press that also has a dropdown arrow on the right of it, To make the menu popup when you click to the left of the arrow this code in the button click handler should do the job.

procedure TForm1.Button1Click(Sender: TObject);
var
  CursorPos: TPoint;
begin
  GetCursorPos(CursorPos);
  PopupMenu1.Popup(CursorPos.X, CursorPos.Y);
end;

in previous versions of Delphi I think you had to use TToolBar.