Delphi的有关菜单的Owner-draw 技术

xiaoye 2000-09-11 10:44:00
我在一本讲述Delphi技术的书上看到有关菜单的Owner-draw 技术,讲得并不复杂。
于是我试验了一个Color菜单,它有三个菜单项:Red,Blue,Green。按书上介绍的程序
运行时应该由三种颜色来代替文字。

在Form 的public部分定义两个消息响应过程:
procedure WmMeasureItem(var Msg: TWmMeasureItem);
message wm_MeasureItem;
procedure WmDrawItem(var Msg: TWmDrawItem);
message wm_DrawItem;

在implementation段编写消息响应过程,还有OnCreate过程,程序如下(按书中所写):

procedure TForm1.FormCreate(Sender: TObject);
var
I: integer;
begin
for I:=0 to Color1.Count-1 do
begin
ModifyMenu(Color1.Handle,Color1.Items[I].menuIndex,
mf_ByPosition or mf_OwnerDraw,Color1.Items[I].Command,
Pointer(I));
end;
end;

procedure TForm1.WmMeasureItem(var Msg: TWmMeasureItem);
begin
inherited;
with Msg.MeasureItemStruct^ do
if CtlType =odt_Menu then
begin
ItemWidth:=80;
ItemHeight:=30;
Msg.Result :=1;
end;
end;

procedure TForm1.WmDrawItem(var Msg: TWmDrawItem);
var
Canvas1: TCanvas;
begin
inherited;
with Msg.DrawItemStruct^ do
if CtlType =odt_Menu then
begin
//create a canvas for painting
Canvas1:=TCanvas.Create;
Canvas1.Handle :=hDC;
try
//set the background color and draw it
if (ods_Selected and ItemState<>0) then
Canvas1.Brush.Color :=clHighlight
else
Canvas1.Brush.Color :=clMenu;

Canvas1.FillRect(rcItem);
case ItemData of
0: Canvas1.Brush.Color :=clRed;
1: Canvas1.Brush.Color :=clGreen;
2: Canvas1.Brush.Color :=clBlue;
end;
Canvas1.Rectangle(rcItem.left +5, rcItem.top +5,
rcItem.Right -10, rcItem.Bottom -10);
finally
Canvas1.Free;
end;
end;
end;

我照着做了却没有预期效果,不知是何原因?
...全文
167 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
PoolD 2000-09-12
  • 打赏
  • 举报
回复
不需要这么麻烦的。
只需要将TMainMenu的OwnerDraw设为true,再响应MenuItem的OnDrawItem事件就可以了。
菜单项的Canvas、Rect等等都在参数里有。Selected参数可以判断鼠标位置是否在菜单项上。很方便。只是快捷键不太好显示(下划线)。
Putao 2000-09-12
  • 打赏
  • 举报
回复
关注
zcw 2000-09-12
  • 打赏
  • 举报
回复
我想不应在create里写,应在OnPaint里写。

5,392

社区成员

发帖
与我相关
我的任务
社区描述
Delphi 开发及应用
社区管理员
  • VCL组件开发及应用社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧