You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Visual Studio C#:为禁用按钮添加提示框,解决鼠标悬停无事件响应问题

为禁用的C# WinForms Button添加悬停提示的解决方案

禁用的Button默认不会触发MouseMove等鼠标事件,但可以通过以下两种常用方法实现悬停提示:

方法一:利用父控件的MouseMove事件结合ToolTip

这种方法无需自定义控件,适合快速实现:

  1. 在窗体上添加一个ToolTip控件(命名为toolTip1)。
  2. 为目标Button设置提示文本:
    // 可直接设置,也可把原因存在Button的Tag属性里后续读取
    toolTip1.SetToolTip(button1, "按钮禁用原因:请先完成用户信息填写");
    
  3. 处理窗体(或Button所在父容器)的MouseMove事件:
    private void ParentControl_MouseMove(object sender, MouseEventArgs e)
    {
        bool tooltipShown = false;
        // 遍历父控件内的所有Button
        foreach (Control ctrl in ((Control)sender).Controls)
        {
            if (ctrl is Button btn && !btn.Enabled)
            {
                Point btnClientPos = btn.PointToClient(e.Location);
                if (btn.ClientRectangle.Contains(btnClientPos))
                {
                    toolTip1.Show(toolTip1.GetToolTip(btn), this, e.Location.X + 10, e.Location.Y + 10);
                    tooltipShown = true;
                    break;
                }
            }
        }
        // 未在禁用Button上时隐藏提示
        if (!tooltipShown)
        {
            toolTip1.Hide(this);
        }
    }
    

方法二:自定义Button控件(推荐复用场景)

通过重写WndProc处理Windows底层鼠标消息,让禁用的Button也能响应鼠标悬停:

using System.Windows.Forms;

public class HintEnabledButton : Button
{
    private readonly ToolTip _tooltip = new ToolTip();
    // 专门用于设置禁用状态下的提示文本
    public string DisabledHintText { get; set; }

    protected override void WndProc(ref Message m)
    {
        const int WM_MOUSEMOVE = 0x0200;
        const int WM_MOUSELEAVE = 0x02A3;

        base.WndProc(ref m);

        if (!Enabled && !string.IsNullOrEmpty(DisabledHintText))
        {
            switch (m.Msg)
            {
                case WM_MOUSEMOVE:
                    Point mousePos = PointToClient(Cursor.Position);
                    if (ClientRectangle.Contains(mousePos))
                    {
                        _tooltip.Show(DisabledHintText, this, mousePos.X + 10, mousePos.Y + 10);
                    }
                    break;
                case WM_MOUSELEAVE:
                    _tooltip.Hide(this);
                    break;
            }
        }
    }
}

使用方式:

  • 编译项目后,自定义的HintEnabledButton会出现在工具箱中。
  • 将其拖到窗体上,设置DisabledHintText属性为禁用原因,当按钮禁用时,鼠标悬停即可显示提示。

内容的提问来源于stack exchange,提问作者Alex

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.23 02:37:29