首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> Delphi

Delphi 客製化工具提示:自訂背景色、字型、字體大小與顏色完整教學

     編輯:Delphi

前言

Windows 標準工具提示(Tooltip)預設淡黃底黑字,千篇一律。Delphi 透過 Application.HintColor 可改背景色,但字體樣式需繼承 THintWindow 並重寫 Create 與 Paint 方法。本文完整示範從零打造專屬 Tooltip 風格。

第一步:改背景色(一行搞定)

procedure TForm1.FormCreate(Sender: TObject);
begin
  Application.HintColor := clRed;  // 背景變紅色
end;

第二步:建立自訂 THintWindow 衍生類別

在 implementation 區前方宣告:

type
  TMyHintWindow = class(THintWindow)
  public
    constructor Create(AOwner: TComponent); override;
    procedure Paint; override;
  end;

重寫 Create:設定字體

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;

重寫 Paint:移除系統強制覆蓋字色

原始 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;

完整測試專案架構

  1. 新建 VCL 專案
  2. Form1 放一個 TButton,設定 ShowHint := True、Hint := '這是自訂工具提示'
  3. 貼上上述類別宣告與方法實作
  4. 在 FormCreate 設定 HintWindowClass 與 Application.HintColor
  5. 執行,滑鼠懸停按鈕觀察效果

進階技巧與注意事項

  • 動態切換風格:可在執行期隨時指派 HintWindowClass := AnotherHintClass 實現情境式 Tooltip
  • 多行支援:DT_WORDBREAK 已啟用,長字串自動換行
  • 雙向語言:DrawTextBiDiModeFlagsReadingOnly 確保 RTL 語言正確顯示
  • 只重寫 Paint 不重寫 Create 可行嗎?:可行,但 Create 中的 Color := $80FFFF(預設淡青背景)會先套用,再被 Application.HintColor 覆蓋,會有一次極短暫的閃爍,重寫 Create 可避免
  • 全域生效:HintWindowClass 為進程全域,影響應用程式所有 Tooltip,若需個別控制需攔截 CM_HINTSHOW 訊息動態建立視窗

原始碼參考:THintWindow 原始實作(Delphi 來源)

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;
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved