2015-12-10 46 views
1

我用这个代码上悬停tooltip来实现,其工作原理与TextBoxComboBoxMaskedTextBox但不是在NumericUpDown。有人知道它为什么不起作用吗?的NumericUpDown没有改变ToolStripStatusLabel时的MouseEnter

public static void addHovertip(ToolStripStatusLabel lb, Control c, string tip) 
     { 

      c.MouseEnter += (sender, e) => 
      { 
       lb.Text = tip; 
       // MessageBox.Show(c.Name); 
      }; 
      c.MouseLeave += (sender, e) => 
      { 
       lb.Text = ""; 

      }; 
     } 

回答

1

我承认Hans Passant的删除答案在创建这个答案时有点帮助。

首先你的代码工作正常。如果您正在处理经常发生的事件(如MouseEvent),则最好在代码中添加一个Debug.WriteLine,以便您可以在调试器输出窗口中看到哪些事件控制哪些事件发生。

主要问题是,由于数字上/下控件是一个控件,它是两个不同的子控件的组合,只要鼠标进入两个子控件之一,就会调用MouseLeave事件。会发生什么情况是:MouseEnter在鼠标碰到控件的单线边界时被调用,MouseLeave在鼠标不在该线上时被调用。在MouseLeave中,您将Label设置为一个静态字符串。这给人的印象是你的代码不起作用。

通过简单地添加一个循环来解决这个问题。这仍然会将标签设置为空字符串,但是如果需要,它也会立即设置为正确的文本。

这是更改后的代码,其中包含调试语句。

public static void addHovertip(ToolStripStatusLabel lb, Control c, string tip) 
    { 
     c.MouseEnter += (sender, e) => 
     { 
      Debug.WriteLine(String.Format("enter {0}", c)); 
      lb.Text = tip; 
     }; 

     c.MouseLeave += (sender, e) => 
     { 
      Debug.WriteLine(String.Format("Leave {0}", c)); 
      lb.Text = ""; 
     }; 

     // iterate over any child controls 
     foreach(Control child in c.Controls) 
     { 
      // and add the hover tip on 
      // those childs as well 
      addHovertip(lb, child, tip); 
     } 
    } 

为了完整这里是我的测试形式的Load事件:

private void Form1_Load(object sender, EventArgs e) 
{ 
    addHovertip((ToolStripStatusLabel) statusStrip1.Items[0], this.numericUpDown1, "fubar"); 
} 

这里是一个gif动画演示的时候,你和缩小数字向上向下控制移动鼠标会发生什么:

numeric up down control and mouse event debug output

+0

感谢,作品像魅力:) – someone

相关问题