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

C++Builder 自訂 Hint 視窗:繼承 THintWindow 打造專屬工具提示風格

     編輯:VC 教學

為什麼要自訂 Hint 視窗?

預設 THintWindow 風格單一,無法滿足品牌色系、圓角邊框、陰影、動畫等現代 UI 需求。透過繼承並重寫關鍵虛擬方法,可完全掌控外觀與行為。

核心類別實現:TCcrunHintWindow

建構子:預設字體與顏色

__fastcall TCcrunHintWindow(TComponent* Owner)
    : THintWindow(Owner)
{
    Canvas->Font->Name = "新細明體";   // 繁體中文預設字體
    Canvas->Font->Color = clBlack;
    Canvas->Font->Size = 9;
}

Paint:自繪背景、邊框、文字

void __fastcall Paint()
{
    TRect rect = ClientRect;
    // 背景填充
    Canvas->Brush->Color = TColor(0xDBB8BA); // 淺粉背景
    Canvas->FillRect(rect);
    // 邊框
    Canvas->Pen->Color = TColor(0x69230E);   // 深棕邊框
    Canvas->Rectangle(rect);
    // 文字區域透明
    Color = clWhite;
    Canvas->Brush->Style = bsClear;
    Canvas->Font->Color = clBlack;
    // 垂直置中繪製
    Canvas->TextOut(4, 
        rect.Bottom/2 - Canvas->TextHeight(Caption)/2, 
        Caption);
}

CreateParams:移除系統預設邊框

void __fastcall CreateParams(TCreateParams &Params)
{
    Params.Style &= ~WS_BORDER; // 關鍵:去掉 WS_BORDER
    THintWindow::CreateParams(Params);
}

ActivateHint:核心定位與形狀控制

void __fastcall ActivateHint(const TRect &Rect, const String AHint)
{
    FActivating = true;
    try {
        Caption = AHint;
        TRect r = Rect;
        // 擴展顯示區域
        r.Left -= 10; r.Right += 10;
        r.Top -= 5; r.Bottom += 5;
        UpdateBoundsRect(r);

        // 螢幕邊界修正
        if (r.Top + Height > Screen->DesktopHeight)
            r.Top = Screen->DesktopHeight - Height;
        if (r.Left + Width > Screen->DesktopWidth)
            r.Left = Screen->DesktopWidth - Width;
        if (r.Left < Screen->DesktopLeft)
            r.Left = Screen->DesktopLeft;
        if (r.Bottom < Screen->DesktopTop)
            r.Bottom = Screen->DesktopTop;

        // 建立圓角區域(可選矩形/圓角)
        HRGN hrgn = CreateRectRgn(0, 0, r.Width(), r.Height());
        // HRGN hrgn = CreateRoundRectRgn(0,0,r.Width(),r.Height(),4,4); // 圓角
        SetWindowRgn(Handle, hrgn, true);

        // 置頂顯示、不搶焦點
        SetWindowPos(Handle, HWND_TOPMOST, r.Left, r.Top, 
                     r.Width(), r.Height(), 
                     SWP_SHOWWINDOW | SWP_NOACTIVATE);
        Invalidate();
    }
    __finally { FActivating = false; }
}

表單套用:一行代碼啟用

__fastcall TForm1::TForm1(TComponent* Owner) : TForm(Owner)
{
    HintWindowClass = __classid(TCcrunHintWindow); // 關鍵:替換預設類別
    ShowHint = true;
    Button1->Hint = "這是一個按鈕";
    Edit1->Hint = "這是一個文本框";
}

進階擴展建議

  • 動畫淡入/淡出: 在 ActivateHint 結合 AnimateWindow API。
  • HTML 格式支援: 解析 AHint 中的簡易標籤(<b>, <color>)。
  • 多螢幕 DPI 感知: 使用 GetDpiForWindow 縮放字體與邊距。
  • 主題切換: 暴露 BorderColor, BackColor, FontColor 屬性供設計時設定。

自訂 Hint 視窗效果圖

繼承 THintWindow 是 C++Builder 客製化工具提示的標準路徑,代碼量小、相容性好、擴展性強。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved