2010-09-26 56 views
13

我正在用Microsoft Blend構建Windows Presentation Foundation控件。WPF Mousedown => No MouseLeave Event

當我按下鼠標左鍵離開控件時,MouseLeave事件不會引發。爲什麼不?

+0

什麼是你的控制裏面?我在想這是因爲對象(例如一個按鈕)在您的控件內部收到MouseDown事件時已將「Mouse.IsCaptured」設置爲true,因此它只處理MouseEvent。 – ASanch 2010-09-26 17:36:26

+0

這只是一個邊框,網格,圖像和2個標籤。那可能嗎? – 2010-09-28 20:28:03

+0

我們遇到同樣的問題(請參閱問題:http://stackoverflow.com/questions/15970248/wpf-mouse-leave-event-doesnt-trigger-with-mouse-down)。所以我在這裏開了一個獎金來吸引注意力。 – SiberianGuy 2013-04-12 13:26:44

回答

7

這是預期的行爲:當你在做的一個關於控制mousedown和離開控制,控制仍保留着「捕獲」在鼠標上,意味着控制器不會觸發MouseLeave-Event。鼠標離開事件將被觸發,一旦Mousebutton被釋放到控件之外。

爲了避免這種情況,你可以簡單的告訴你的控制不捕獲鼠標都:

private void ControlMouseDown(System.Object sender, System.Windows.Forms.MouseEventArgs e) 
{ 
    Control control = (Control) sender; 
    control.Capture = false; //release capture. 
} 

現在MouseLeave事件會即使在按下按鈕移出時觸發。

如果您需要捕獲內部的控制,就需要投入更多的精力:

  • 開始手動跟蹤mouseposition,當按下鼠標鍵

  • 比較的位置與TopLeftSize有問題的控件的屬性。

  • 決定是否需要停止控制捕獲鼠標。

    public partial class Form1 : Form 
    { 
    private Point point; 
    private Boolean myCapture = false; 
    
    public Form1() 
    { 
        InitializeComponent(); 
    } 
    
    private void button1_MouseDown(object sender, MouseEventArgs e) 
    { 
        myCapture = true; 
    } 
    
    private void button1_MouseMove(object sender, MouseEventArgs e) 
    { 
        if (myCapture) 
        { 
         point = Cursor.Position; 
    
         if (!(point.X > button1.Left && point.X < button1.Left + button1.Size.Width && point.Y > button1.Top && point.Y < button1.Top + button1.Size.Height)) 
         { 
          button1.Capture = false; //this will release the capture and trigger the MouseLeave event immediately. 
          myCapture = false; 
         } 
        } 
    } 
    
    private void button1_MouseLeave(object sender, EventArgs e) 
    { 
        MessageBox.Show("Mouse leaving"); 
    } 
    

    }

當然

你需要的MouseUp上停止自己的跟蹤(myCapture=false;)。忘記了一個:)

+1

但是,如果我在鼠標離開整個窗口時需要提升MouseLeave,該怎麼辦?當鼠標不在Window中時,我想我不會收到MouveMouve事件,所以基於MouseMove的解決方案將無法工作。或者我錯了? – SiberianGuy 2013-04-12 15:14:34

+0

@Idsa它也適用於Forms。 – dognose 2013-04-15 08:53:28

+1

但我們在這裏討論WPF。我懷疑它會適用於WPF窗口 – SiberianGuy 2013-04-15 11:34:26

1

而且的完整性和歷史的原因(不是賞金 - 它沒有任何意義有兩個重複的問題 - 你或許應該將其移動到一個,如果不是太晚了)...

我做了使用global mouse hook這裏(方法2)
WPF: mouse leave event doesn't trigger with mouse down

,徹底解決和簡化其用途 - 比如 - 您可以通過綁定到您的視圖模型命令使用

my:Hooks.EnterCommand="{Binding EnterCommand}" 
my:Hooks.LeaveCommand="{Binding LeaveCommand}" 
my:Hooks.MouseMoveCommand="{Binding MoveCommand}" 

...更多細節在那裏