views:

73

answers:

1

Hello,

I have the following code

  • xaml

    <Canvas x:Name="LayoutRoot" >
        <Rectangle Canvas.Left="40" Canvas.Top="40" Width="20" Height="20" Name="rec" Fill="Red" MouseLeftButtonDown="rec_MouseLeftButtonDown"   MouseMove="rec_MouseMove" />
    </Canvas>
    

  • code behind

public partial class MainPage : UserControl { public MainPage() { InitializeComponent(); }

        public Point LastDragPosition { get; set; }
        private bool isDragging;

        private void rec_MouseMove(object sender, MouseEventArgs e)
        {
            if(!isDragging)
            {
                return;
            }

            var position = e.GetPosition(rec as UIElement);

            var newPosition = new Point(
                Canvas.GetLeft(rec) + position.X - LastDragPosition.X,
                Canvas.GetTop(rec) + position.Y - LastDragPosition.Y);

            Canvas.SetLeft(rec, newPosition.X);
            Canvas.SetTop(rec, newPosition.Y);

            LastDragPosition = e.GetPosition(rec as UIElement);
        }

        private void rec_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            isDragging = true;
            LastDragPosition = e.GetPosition(sender as UIElement);
            rec.CaptureMouse();
        }
    }

This issue is the rectangle follows the mouse if the mouse left button is down, but I would like the rectangle to move even when the mouse left button isn't down. It works, but if you move the mouse very slowly. If you move the mouse to quickly the rectangle stops moving (is the mouse capture lost ?)

Cheers,

A: 

Looks like it can't be done. According to the docs of CaptureMouse, the left button must be pressed. "The left mouse button is in a pressed (down) state."

Mrt