【问题标题】:Winforms event when a mouse leaves a control鼠标离开控件时的 Winforms 事件
【发布时间】:2013-11-11 04:05:26
【问题描述】:

我有一个覆盖在其他控件之上的用户控件。一个按钮将其打开,我希望它在鼠标离开时隐藏(Visible = false)。我应该使用什么事件?我试过Leave,但只有在我手动隐藏它之后才会触发。我也想过MouseLeave,但从未被解雇。

编辑:控件由ListViewPanel 组成,其中包含一堆按钮。它们直接停靠在控件中,没有顶级容器。

【问题讨论】:

  • MouseLeave 应该可以工作,你能发布你的代码吗?你确定你知道如何为MouseLeave 事件注册一些处理程序吗?你能多谈谈你的控件的layout,尤其是你的UserControl
  • 增加了控制权。事件处理器是用VS设计器添加的,应该不会错。

标签: c# winforms events user-controls


【解决方案1】:

UserControl 实际上是一个面板,上面有一些控件,以方便和易于重用(它具有设计时支持的优势)。事实上,当您将鼠标移出UserControl 时,其子控件之一会触发MouseLeave,而不是UserControl 本身。我认为您必须像这样为您的UserControl 实现一些Application-wide MouseLeave

public partial class YourUserControl : UserControl, IMessageFilter {
  public YourUserControl(){
    InitializeComponent();
    Application.AddMessageFilter(this);
  }
  bool entered;
  public bool PreFilterMessage(ref Message m) {
    if (m.Msg == 0x2a3 && entered) return true;//discard the default MouseLeave inside         
    if (m.Msg == 0x200) {                
      Control c = Control.FromHandle(m.HWnd);
      if (Contains(c) || c == this) {                    
         if (!entered) {
            OnMouseEnter(EventArgs.Empty);
            entered = true;                  
          }                   
      } else if (entered) {
         OnMouseLeave(EventArgs.Empty);
         entered = false;                    
      }
    }
    return false;
  }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-05-17
    • 2014-08-29
    • 1970-01-01
    • 2013-04-04
    • 1970-01-01
    • 2014-08-01
    • 1970-01-01
    相关资源
    最近更新 更多