禁用按钮

时间:2015-12-22 01:31:56

标签: c# winforms

我在某个时候发布了这个问题,有人将其标记为DUPLICATE。但是当我向他询问有关该帖子应该有答案的问题时,他没有做出任何正确的解释。因此,请在标记或投票前仔细阅读此问题。

我的问题是关于在禁用的按钮上显示工具提示。

this.btnMy.Enabled = false;

我有一个按钮,放在一个面板内,并附有一个工具提示。现在,当按钮启用时,一切正常。

但如果按钮禁用,则工具提示不起作用。这似乎是标准行为。

现在我想在按钮禁用时显示工具提示。所以我做了以下事情。

private ToolTip m_tooltip = new ToolTip();
private bool toolTipShown = false;
private button btnMy;

m_tooltip.InitialDelay = 0;
m_tooltip.ShowAlways = true;

 private void myForm_MouseMove(object sender, MouseEventArgs e)
        {

            if (this.btnMy == FindControlAtCursor(this))
            {
                if (!toolTipShown)
                {
                    m_tooltip.Show("MyToolTip", this.btnMy, e.Location);
                    toolTipShown = true;
                }
            }
            else
            {
                m_tooltip.Hide(this.btnGiven);
                toolTipShown = false;
            }
        }

当按钮位于面板内部时,我必须使用其他几个函数来找到鼠标悬停时的确切按钮控件。

public static Control FindControlAtPoint(Control container, Point pos)
        {
            Control child;
            foreach (Control c in container.Controls)
            {
                if (c.Visible && c.Bounds.Contains(pos))
                {
                    child = FindControlAtPoint(c, new Point(pos.X - c.Left, pos.Y - c.Top));
                    if (child == null) return c;
                    else return child;
                }
            }
            return null;
        }

        public static Control FindControlAtCursor(Form form)
        {
            Point pos = Cursor.Position;
            if (form.Bounds.Contains(pos))
                return FindControlAtPoint(form, form.PointToClient(Cursor.Position));
            return null;
        }

现在,当我调试时,我可以看到代码找到正确的按钮并尝试调用ToolTip.Show,但由于某种原因它没有显示。

调试时,我看到弹出一个小工具提示。其他明智的发布模式,根本没有显示任何内容。

有什么想法吗?

2 个答案:

答案 0 :(得分:1)

我不会争论它是否重复(尽管在评论中指出HABO看起来与How can I show a tooltip on a disabled button?非常相似)。另外,我不打算讨论整个代码。

主要问题在于此行

m_tooltip.Show("MyToolTip", this.btnMy, e.Location);

您使用ToolTip.Show参数的状态point重载的documentation

  

包含相对于关联控制窗口左上角的偏移量(以像素为单位)的点,以显示工具提示。

当您传递相对于表单的点时。

为了解决这个问题,你应该使用类似的东西

var pos = this.btnMy.PointToClient(this.PointToScreen(e.Location));
m_tooltip.Show("MyToolTip", this.btnMy, pos);

答案 1 :(得分:0)

当鼠标位于子控件或面板上时,MouseMove事件不会触发,因此您最好使用Timer:

private void timer1_Tick(object sender, EventArgs e) {
  Control c = FindControlAtPoint(this, this.PointToClient(Control.MousePosition));
  if (c != null) {
    Point p = c.PointToClient(Control.MousePosition);
    p.Offset(10, 10);
    m_tooltip.Show("Found " + c.Name, c, p);
    m_tooltip.Active = true;
  } else {
    m_tooltip.Active = false;
  }
}