預設 THintWindow 風格單一,無法滿足品牌色系、圓角邊框、陰影、動畫等現代 UI 需求。透過繼承並重寫關鍵虛擬方法,可完全掌控外觀與行為。
TCcrunHintWindow__fastcall TCcrunHintWindow(TComponent* Owner)
: THintWindow(Owner)
{
Canvas->Font->Name = "新細明體"; // 繁體中文預設字體
Canvas->Font->Color = clBlack;
Canvas->Font->Size = 9;
}
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);
}
void __fastcall CreateParams(TCreateParams &Params)
{
Params.Style &= ~WS_BORDER; // 關鍵:去掉 WS_BORDER
THintWindow::CreateParams(Params);
}
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。AHint 中的簡易標籤(<b>, <color>)。GetDpiForWindow 縮放字體與邊距。BorderColor, BackColor, FontColor 屬性供設計時設定。
繼承 THintWindow 是 C++Builder 客製化工具提示的標準路徑,代碼量小、相容性好、擴展性強。