VCL 的 THintWindow 提供基礎提示功能,但外觀固定。透過繼承並覆寫關鍵虛擬函數,可完全掌控提示視窗的繪製、形狀、位置與行為。本文展示一個完整的自訂提示類別 TCcrunHintWindow,支援圓角矩形、自訂邊框/背景色、字型設定、螢幕邊界自動修正與 Z-order 置頂。
class TCcrunHintWindow : public THintWindow
{
bool FActivating;
public:
__fastcall TCcrunHintWindow(TComponent* Owner);
virtual void __fastcall Paint();
virtual void __fastcall NCPaint(HDC hdc);
virtual void __fastcall CreateParams(TCreateParams &Params);
virtual void __fastcall ActivateHint(const TRect &Rect, const String &AHint);
};
__fastcall TCcrunHintWindow(TComponent* Owner) : THintWindow(Owner)
{
Canvas->Font->Name = L"新細明體";
Canvas->Font->Color = clBlack;
Canvas->Font->Size = 9;
}
void __fastcall Paint()
{
TRect rect = ClientRect;
Canvas->Brush->Color = 0xDBB8BA; // 邊框色
Canvas->FillRect(rect);
Canvas->Pen->Color = 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 NCPaint(HDC hdc) { Invalidate(); }
簡單呼叫 Invalidate() 觸發 Paint() 重繪,避免預設 NC 繪製干擾。
void __fastcall CreateParams(TCreateParams &Params)
{
Params.Style = Params.Style & ~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; }
}
在表單建構函數指定 HintWindowClass:
__fastcall TForm1::TForm1(TComponent* Owner) : TForm(Owner)
{
HintWindowClass = __classid(TCcrunHintWindow);
ShowHint = true;
Button1->Hint = L"這是一個按鈕";
Edit1->Hint = L"這是一個文字框";
}
ActivateHint 中加入 AnimateWindow 呼叫實現淡入/滑入。TRichEdit 或自訂繪製支援富文字。GetSysColor、UxTheme)自動調整配色。MonitorFromRect 取得正確桌面邊界。繼承 THintWindow 並覆寫 Paint、CreateParams、ActivateHint 三大核心虛擬函數,即可打造完全符合專案視覺規範的提示視窗。本範例展示圓角、邊框、字型、定位與置頂的完整控制,可直接套用於專案中。