2013-10-31 144 views
0

我有一個覆蓋其他控件的用戶控件。一個按鈕會將其提起,我希望它在鼠標離開時隱藏(Visible = false)。我應該使用什麼事件?我試過Leave,但只有在手動隱藏後纔會觸發。我也想過MouseLeave,但那從未被解僱過。鼠標離開控件時Winforms事件

編輯:該控件由一個ListView和一個Panel與一堆按鈕組成。他們直接停靠在控制中,沒有頂層容器。

+0

'MouseLeave'應該工作,你可以發佈您的代碼?你確定你知道如何爲'MouseLeave'事件註冊一些處理程序嗎?你可以多談談一下你的控件的佈局,特別是你的'UserControl'。 –

+0

增加了控制俯視圖。事件處理程序是使用VS設計器添加的,它不應該是錯誤的。 –

回答

0

UserControl實際上是一個控制面板上的一些控件,方便和易於重複使用(它具有設計時支持的優點)。事實上,當您將鼠標移出UserControl時,其中一個子控件觸發MouseLeave,而不是UserControl本身。我認爲你必須實現某種Application-wide MouseLeaveUserControl這樣的:

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; 
    } 
}