Search code examples
c#wpfdrag-and-dropmouseeventmousecapture

Mouse events for captured element stop firing while dragging


I have some code that draws some points on the screen and then allows them to be dragged while holding the left mouse button. This kinda works except constantly the mouse events stop firing and the point being dragged stops moving.

Because all of the events stop being caught(for some unknown reason), that means the user can release the left mouse button without anything happening.

The weird thing is that the user can then reposition the mouse over the point and it will start dragging again without holding the left mouse button down. It makes for a very poor user experience.

What is going on?

pinPoint.MouseLeftButtonDown += Point_MouseLeftButtonDown;
pinPoint.MouseLeftButtonUp += Point_MouseLeftButtonUp;
pinPoint.MouseMove += Point_MouseMove;

.
.
.

void Point_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
    ((UIElement)sender).CaptureMouse();
    if (_isDragging == false)
    {
        _isDragging = true;
    }
}

void Point_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{
    _isDragging = false;
    ((UIElement)sender).ReleaseMouseCapture();
}

void Point_MouseMove(object sender, MouseEventArgs e)
{
    //where the point gets moved and some other logic
    //possibly this logic takes too long?
}

Solution

  • I've found a solution that works. I've still got no idea why it is continually losing the MouseCapture though.

    pinPoint.LostMouseCapture += Point_LostMouseCapture;
    
    .
    .
    .
    
    void Point_LostMouseCapture(object sender, MouseEventArgs e)
    {
        //if we lost the capture but we are still dragging then just recapture it
        if (_isDragging)
        {
            ((UIElement)sender).CaptureMouse();
        }
    }