在网上有很多文章都提到怎样在菜单中加入背景图片,可是都没有一个完整的回答,也没有一个比较完整的例子。当然csdn曾经有一个高人说过这个问题,而且在程序员大本营2000版中也有收藏。我参考了一些方法和技巧,当然包括国外的了,写下了如下的代码,希望能够满足大家的要求,不过不是很完善,如果有哪位大侠修改过,不妨也将修改过的代码贴出来,大家共享!为了在menu控件中加入背景图片,没有直接的方法,都的靠自己动手画,因为menu控件没有canvas属性,所以只能自己动手了!这个东西我也是菜鸟一只,说不出什么高深的东西,如果有什么问题可以发信给我,我们共同探讨:[email protected],源代码如下:
unit FMain;
interface
uses
Windows, Graphics, Forms, Menus, Classes;
type
TfrmMain = class(TForm)
mnuPopup: TPopupMenu;
MainMenu1: TMainMenu;
sdfsdf1: TMenuItem;
sdfsdf2: TMenuItem;
dfgdfg1: TMenuItem;
dfgdfg2: TMenuItem;
N1: TMenuItem;
werwer1: TMenuItem;
procedure DrawMenu(Sender: TObject; ACanvas: TCanvas; ARect: TRect; State: TOwnerDrawState);
procedure MeasureMenu(Sender: TObject; ACanvas: TCanvas; var Width, Height: Integer);
procedure FormCreate(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
end;
var
frmMain: TfrmMain;
bmp1:tbitmap;
implementation
{$R *.DFM}
procedure TfrmMain.DrawMenu(Sender: TObject; ACanvas: TCanvas; ARect: TRect; State: TOwnerDrawState);
var
cTemp: TCanvas;
sText: String;
mWnd: HWND;
rMenu: TRect;
begin
ACanvas.BrushCopy(ARect, bmp1, ARect, clBlack);
ACanvas.Brush.Style := bsclear;
sText := TMenuItem(Sender).Caption;
acanvas.Font.Color:=clred;
with ACanvas do begin
if odSelected in State then begin
pen.Style:=psInsideFrame;
Brush.Color := RGB(110, 131, 184);
Pen.Color := RGB(47, 60, 93);
Rectangle(ARect);
end;
if sText = '-' then begin
// Draw line
ACanvas.Pen.Color := RGB(0, 0, 0);
MoveTo(ARect.Left, ARect.Top + ((ARect.Bottom - ARect.Top) div 2));
LineTo(ARect.Right, ARect.Top + ((ARect.Bottom - ARect.Top) div 2));
end else begin
// Draw text
Inc(ARect.Left, 12);
DrawText(Handle, PChar(sText), Length(sText), ARect, DT_LEFT or DT_VCENTER or DT_SINGLELINE);
end;
end;
// 画边框的,效果是平面的
mWnd := WindowFromDC(ACanvas.Handle);
if mWnd <> Self.Handle then begin
cTemp := TCanvas.Create();
cTemp.Handle := GetDC(0);
Windows.GetWindowRect(mWnd, rMenu);
cTemp.Brush.Color := RGB(120, 120, 120);
cTemp.FrameRect(rMenu);
InflateRect(rMenu, -1, -1);
cTemp.Brush.Color := RGB(240, 240, 240);
cTemp.FrameRect(rMenu);
InflateRect(rMenu, -1, -1);
cTemp.FrameRect(rMenu);
ReleaseDC(0, cTemp.Handle);
cTemp.Free();
end;
end;
procedure TfrmMain.MeasureMenu(Sender: TObject; ACanvas: TCanvas; var Width, Height: Integer);
begin
Inc(Width,50);//调整菜单的宽度
inc(height,15);//调整每一个item的高度,这一句可以不要,使用默认值
end;
procedure TfrmMain.FormCreate(Sender: TObject);
begin
bmp1:=tbitmap.Create;
bmp1.loadfromfile('e:\aaa.bmp');
end;
procedure TfrmMain.FormClose(Sender: TObject; var Action: TCloseAction);
begin
bmp1.Free;
end;
end.
本文地址:http://com.8s8s.com/it/it5730.htm