Windows 標準工具提示(Tooltip)預設淡黃底黑字,千篇一律。Delphi 透過 Application.HintColor 可改背景色,但字體樣式需繼承 THintWindow 並重寫 Create 與 Paint 方法。本文完整示範從零打造專屬 Tooltip 風格。
procedure TForm1.FormCreate(Sender: TObject);
begin
Application.HintColor := clRed; // 背景變紅色
end;
在 implementation 區前方宣告:
type
TMyHintWindow = class(THintWindow)
public
constructor Create(AOwner: TComponent); override;
procedure Paint; override;
end;
constructor TMyHintWindow.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
with Canvas do
begin
Font.Name := '標楷體'; // 字型
Font.Color := clYellow; // 字色
Font.Size := 20; // 字級
Brush.Style := bsClear; // 透明筆刷
end;
end;
原始 THintWindow.Paint 會執行 Canvas.Font.Color := clInfoText 覆蓋你的設定,必須完整複製原始碼並刪除該行:
procedure TMyHintWindow.Paint;
var
R: TRect;
begin
R := ClientRect;
InflateRect(R, -2, -2); // 內縮 2 像素邊距
// 關鍵:註解掉 Canvas.Font.Color := clInfoText;
DrawText(Canvas.Handle, PChar(Caption), -1, R,
DT_LEFT or DT_NOPREFIX or DT_WORDBREAK or DrawTextBiDiModeFlagsReadingOnly);
end;
Delphi 內建全域變數 HintWindowClass: THintWindowClass = THintWindow,在 FormCreate 指向自訂類別:
procedure TForm1.FormCreate(Sender: TObject);
begin
Application.HintColor := clNavy; // 背景深藍
HintWindowClass := TMyHintWindow; // 切換類別
end;
TButton,設定 ShowHint := True、Hint := '這是自訂工具提示'FormCreate 設定 HintWindowClass 與 Application.HintColorHintWindowClass := AnotherHintClass 實現情境式 TooltipDT_WORDBREAK 已啟用,長字串自動換行DrawTextBiDiModeFlagsReadingOnly 確保 RTL 語言正確顯示Create 中的 Color := $80FFFF(預設淡青背景)會先套用,再被 Application.HintColor 覆蓋,會有一次極短暫的閃爍,重寫 Create 可避免HintWindowClass 為進程全域,影響應用程式所有 Tooltip,若需個別控制需攔截 CM_HINTSHOW 訊息動態建立視窗constructor THintWindow.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
Color := $80FFFF; // 預設背景色
Canvas.Font := Screen.HintFont; // 繼承系統 Hint 字型
Canvas.Brush.Style := bsClear;
end;
procedure THintWindow.Paint;
var
R: TRect;
begin
R := ClientRect;
Inc(R.Left, 2); Inc(R.Top, 2);
Canvas.Font.Color := clInfoText; // 關鍵:強制覆蓋字色
DrawText(Canvas.Handle, PChar(Caption), -1, R,
DT_LEFT or DT_NOPREFIX or DT_WORDBREAK or DrawTextBiDiModeFlagsReadingOnly);
end;