Главная страница | назад





Article #27128: How to custom draw menu items

Custom drawing of menu items
By Corbin Dunn
Delphi Developer Support

First, take the opportunity to download the complete source for this project from CodeCentral.

While working an application I wanted to have a custom drawn popup menu that separated the menu into a series of groups. This would allow the user to easily differentiate each group. With Delphi, this is very easy to do. I put a TPopupMenu on my form and set the OwnerDraw property to True. I then set the OnDrawItem event for all of my "header" menu items. Then, I added the following code:

procedure TForm1.CustomMenu1DrawItem(Sender: TObject; ACanvas: TCanvas;
ARect: TRect; Selected: Boolean);
var
LeftPos: Integer;
TopPos: Integer;
TextLength: Integer;
Text: string;
begin
Text := (Sender as TMenuItem).Caption;
ACanvas.Brush.Color := clGray;
ACanvas.FillRect(ARect);
ACanvas.Font.Color := clWhite;
ACanvas.Font.Style := [fsBold];
// Draw right in the middle of the menu
TopPos := ARect.Top +
(ARect.Bottom — ARect.Top — ACanvas.TextHeight('W')) div 2;
TextLength := Length(Text);
if TextLength > (ARect.Right — ARect.Left) then
LeftPos := ARect.Left + 3
else
LeftPos := ARect.Left + (ARect.Right — ARect.Left -
ACanvas.TextWidth(Text)) div 2;
ACanvas.TextOut(LeftPos, TopPos, Text);
end;
Pretty simple!

Last Modified: 26-MAR-01