hi guys,
i'm desperatly trying to move a shape on a canvas with the mouse!! it does not work quite good.
when i click on the left mouse button, i want my shape to move along with my pointer.
Here are my functions, i tryed to follow this : http://stackoverflow.com/questions/437639/how-do-i-use-capturemouse-or-mouse-capture-in-my-c-wpf-application
So, when my left button is down, i capture the mouse for the shape :
private void canvas1_MouseLeftButtonDown(object sender, System.Windows.Input.MouseEventArgs e)
{
Console.WriteLine("down");
Canvas canvas = (Canvas)sender;
Point p = e.GetPosition(canvas);
for (int index = 0; index < VisualTreeHelper.GetChildrenCount((DependencyObject)canvas); index++)
{
if ( VisualTreeHelper.HitTest(canvas,p) != null)
{
Shape shape = VisualTreeHelper.GetChild(canvas, index) as Shape;
Console.WriteLine("capture {0}", shape.ToString());
shape.MouseMove += new System.Windows.Input.MouseEventHandler(shape_MouseMove);
shape.CaptureMouse();
}
}
}
When the mouse moves, i check if the object is captured (the shape), and if so, i redraw the content :
private void shape_MouseMove(object sender, System.Windows.Input.MouseEventArgs e)
{
Shape s = sender as Shape;
if (s.IsMouseCaptured == true)
{
Point p = e.GetPosition((IInputElement)sender);
Console.WriteLine("{0} -- {1} -- {2}", s.ToString(), p.ToString(), s.Parent.ToString());
Canvas canvas = s.Parent as Canvas;
canvas.Children.Remove(s);
Canvas.SetTop(s, p.Y);
Canvas.SetLeft(s, p.X);
canvas.Children.Add(s);
}
}
Finally, when my left mouse button is up again, i release the mouse capture for the shape:
private void canvas1_MouseLeftButtonUp(object sender, System.Windows.Input.MouseEventArgs e)
{
for (int index = 0; index < VisualTreeHelper.GetChildrenCount((DependencyObject)sender); index++)
{
Shape s = VisualTreeHelper.GetChild((DependencyObject)sender, index) as Shape;
if (s.IsMouseCaptured == true)
{
Console.WriteLine("release");
s.ReleaseMouseCapture();
}
}
}
However, i kind of works but the movement of the shape is jiggly, it seems to be in conflit with something. As a result, the object shape follows my mouse pointer but it constantly jumps to other random locations on the canvas ....
What is wrong ??
please help me!! :)
cheers