首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> .NET 網頁程式設計 >> C# >> 關於C#

C# WinForms ToolTip 完整使用指南:從基礎到進階樣式客製化

     編輯:關於C#

ToolTip 基本用法

ToolTip 元件提供滑鼠懸停顯示提示文字的功能,屬於 System.Windows.Forms 命名空間。最簡單用法只需兩行:

var tip = new ToolTip();
tip.SetToolTip(txtUserId, "請輸入 6-12 位英數字元");

常用屬性速查表

屬性說明預設值
AutoPopDelay提示保持顯示毫秒數5000
InitialDelay滑鼠停留多久才出現提示500
ReshowDelay在同一控件間移動時的延遲100
ShowAlways即使表單失去焦點仍顯示false
IsBalloon氣球樣式(帶尾巴)false
ToolTipIcon圖示:None/Info/Warning/ErrorNone
ToolTipTitle提示標題(需 IsBalloon=true 或設定 Icon)""
ForeColor/BackColor前景/背景色系統色
UseAnimation/UseFading動畫/淡入淡出效果true

進階樣式客製化範例

var tip = new ToolTip
{
    // 視覺風格
    IsBalloon = true,
    ToolTipIcon = ToolTipIcon.Info,
    ToolTipTitle = "輸入提示",
    BackColor = Color.LightYellow,
    ForeColor = Color.DarkBlue,

    // 時間控制
    AutoPopDelay = 8000,
    InitialDelay = 300,
    ReshowDelay = 50,
    ShowAlways = true,

    // 動畫
    UseAnimation = true,
    UseFading = true
};

// 為多個控件批次設定
tip.SetToolTip(txtEmail, "格式: user@domain.com");
tip.SetToolTip(txtPhone, "格式: 09xx-xxxxxx");
tip.SetToolTip(btnSubmit, "按下送出表單");

動態更新提示內容

若需根據驗證結果即時變更提示:

private void txtEmail_TextChanged(object sender, EventArgs e)
{
    string msg = IsValidEmail(txtEmail.Text)
        ? "格式正確 ✓"
        : "請輸入有效 Email 格式";
    toolTip1.SetToolTip(txtEmail, msg);
}

常見問題與解決

問題原因解決
提示不顯示控件 Enabled=false 或 Visible=false改用 ReadOnly 或自訂繪製
顯示位置偏移DPI 縮放 / 巢狀容器設定 OwnerDraw=true 手繪位置
多行文字不換行預設單行字串加入 \n 或用 OwnerDraw 量測繪製
記憶體洩漏動態建立 ToolTip 未 Dispose表單關閉時 tip.Dispose() 或用元件托管

OwnerDraw 完全自訂外觀(進階)

var tip = new ToolTip { OwnerDraw = true };
tip.Draw += (s, e) =>
{
    e.DrawBackground();
    e.DrawBorder();
    using (var font = new Font("微軟正黑體", 10f))
    using (var brush = new SolidBrush(Color.DarkSlateGray))
    {
        e.Graphics.DrawString(e.ToolTipText, font, brush, e.Bounds);
    }
};

總結

ToolTip 是提升使用者體驗最低成本的元件。善用 IsBalloon、ToolTipIcon、ToolTipTitle 即可獲得專業外觀;搭配 AutoPopDelay 等時間屬性微調體驗;複雜場景可開啟 OwnerDraw 完全掌控渲染。記得在表單關閉時釋放資源,避免非託管洩漏。

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