wpf mousecapture being force released immediately

944 Views Asked by At

I'm building a user control that includes a flyout panel.

When I click the button to open the panel I'm trying to capture the mouse so that I can detect if the user clicks off the flyout panel so I can close it.

But right after I capture the mouse, I get a lost mousecapture event and I can't detect the clicks outside of the panel.

here is where I detect the straight open close click

private void Grid_MouseUP(object sender, MouseButtonEventArgs e)
{
if (indicatorVM != null)
{
    if (indicatorVM.SettingsFlyoutVisibility == Visibility.Collapsed)
    {
        doRelease = false;
        indicatorVM.SettingsFlyoutVisibility = Visibility.Visible;
        bool result = this.CaptureMouse();
        result = Mouse.Capture(this, CaptureMode.SubTree);
    }
    else
    {
        doRelease = true;
        indicatorVM.SettingsFlyoutVisibility = Visibility.Collapsed;
        this.ReleaseMouseCapture();
    }
}

}

If I wire into the capture lost event, it's hit immediately after the flyout opens. When I check the result variable, regardless of how I capture the mouse, the result is true, so it appears to be working correctly.

Any ideas?

1

There are 1 best solutions below

0
On

First, try an UpdateLayout right after setting indicatorVM's visibility to Visible, before you capture the mouse. This will avoid having the layout change after you capture the mouse, which is probably what is stealing the capture from you. My second suggestion is to slightly postpone the capture with a Dispatcher Invoke, like this:

Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Normal, (Action)delegate()
{
    bool result = this.CaptureMouse();
    result = Mouse.Capture(this, CaptureMode.SubTree);
 });

The capture will then be after the layout consequences.