如何在CodeGear 2007的VCL应用程序中移除BitBtn的边框?
如何在CodeGear 2007的VCL应用中让BitBtn只显示Glyph(隐藏边框和背景)
嘿,我完全懂你不想折腾底层HWND操作的心情——VCL本身就给我们封装好了简单的方法,不用去直接调用CreateWindow那种复杂的API。下面给你两种实用的方案,都能实现只显示Glyph、去掉边框和背景的效果:
方案1:利用BitBtn的自有属性+OnPaint事件快速实现
这种方法不用写自定义控件,直接在现有BitBtn上设置属性并写几行代码就行:
先设置BitBtn的这些属性:
Style→bsOwnerDraw(开启自绘模式,对应你提到的BS_OWNERDRAW,但VCL已经帮我们封装好了)Flat→TrueTransparent→TrueMargin→0Spacing→0Caption→ 清空(避免显示文字)
给BitBtn添加
OnPaint事件,写上以下代码:
procedure TForm1.BitBtn1Paint(Sender: TObject); var GlyphRect: TRect; begin with TBitBtn(Sender) do begin // 如果需要完全透明,就用父控件的颜色填充背景 if Transparent then Parent.ColorToCanvas(Canvas, ClientRect); // 居中绘制Glyph if Assigned(Glyph) then begin GlyphRect.Left := (ClientWidth - Glyph.Width) div 2; GlyphRect.Top := (ClientHeight - Glyph.Height) div 2; GlyphRect.Right := GlyphRect.Left + Glyph.Width; GlyphRect.Bottom := GlyphRect.Top + Glyph.Height; Canvas.Draw(GlyphRect.Left, GlyphRect.Top, Glyph); end; end; end;
这样设置后,BitBtn就只会显示你的Glyph,边框和背景都不见了。
方案2:自定义可复用的Glyph-only按钮控件
如果你的应用里需要多个这样的按钮,自定义一个控件会更方便,后续直接拖用就行:
- 新建一个单元(比如
CustomGlyphBtn.pas),写入以下代码:
unit CustomGlyphBtn; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, Buttons; type TGlyphOnlyBtn = class(TBitBtn) protected procedure Paint; override; public constructor Create(AOwner: TComponent); override; end; implementation constructor TGlyphOnlyBtn.Create(AOwner: TComponent); begin inherited Create(AOwner); // 默认设置好需要的属性 Style := bsOwnerDraw; Flat := True; Transparent := True; Margin := 0; Spacing := 0; Caption := ''; end; procedure TGlyphOnlyBtn.Paint; var GlyphRect: TRect; begin // 跳过继承的Paint方法,避免绘制边框和背景 if Transparent then Parent.ColorToCanvas(Canvas, ClientRect); // 居中绘制Glyph if Assigned(Glyph) then begin GlyphRect.Left := (ClientWidth - Glyph.Width) div 2; GlyphRect.Top := (ClientHeight - Glyph.Height) div 2; Canvas.Draw(GlyphRect.Left, GlyphRect.Top, Glyph); end; end; end.
- 把这个单元添加到你的工程里,然后在IDE的组件面板里就能找到
TGlyphOnlyBtn,拖到窗体上直接用就行,还能在设计时设置Glyph。
额外优化:添加鼠标交互效果
如果需要按钮有悬停/点击的反馈,可以提前准备两张Glyph(正常状态和悬停状态),然后添加鼠标事件:
// 假设你已经在窗体上加载了NormalGlyph和HoverGlyph两个TBitmap procedure TForm1.GlyphOnlyBtn1MouseEnter(Sender: TObject); begin TGlyphOnlyBtn(Sender).Glyph := HoverGlyph; end; procedure TForm1.GlyphOnlyBtn1MouseLeave(Sender: TObject); begin TGlyphOnlyBtn(Sender).Glyph := NormalGlyph; end;
这些方法在CodeGear 2007(也就是Delphi 2007)里完全兼容,不用去碰底层的CreateWindow,省心多了~
内容的提问来源于stack exchange,提问作者kevin
相关产品推荐
相关产品推荐

