C# – How to move controls on the page at runtimne using mouse-Collection of common programming errors
Hi! :),
I’m building a metro style app and I’d like the user could move textblocks on the page of the app at runtime clicking on them and moving the mouse on the page.
For this purpose I developed the code below.
Actually, It does the trick but there’s a problem. The selected textblock moves more than the mouse pointer. For example if I move the mouse on the right along very few pixels, the selected textblock moves on the right along lots of pixels. So the textblock movements amplify the mouse movements. I’d like the textblock exactly follows the movements of the mouse pointer after clicking on it.
I hope you can find the problem in my code.
private bool isTracing = false; private Point previousLocation; void MouseDown(object sender, PointerRoutedEventArgs e) { ((TextBlock)sender).CapturePointer(e.Pointer); Debug.WriteLine("PointerPressed"); previousLocation = e.GetCurrentPoint(this).Position; // Pointer position isTracing = true; Window.Current.CoreWindow.PointerCursor = new Windows.UI.Core.CoreCursor(Windows.UI.Core.CoreCursorType.Hand, 1); } void MouseMove(object sender, PointerRoutedEventArgs e) { Debug.WriteLine("PointerMoved"); Debug.WriteLine(e.GetCurrentPoint(this).Position); if (isTracing) { Debug.WriteLine("isTracing"); var activeControl = (TextBlock)sender; // Selected textblock Thickness margin = activeControl.Margin; // Margins of the selected textblock Thickness newMargin = new Thickness(); Point currentLocation = e.GetCurrentPoint(this).Position; // Pointer position newMargin.Left = margin.Left + (currentLocation.X - previousLocation.X); newMargin.Top = margin.Top + (currentLocation.Y - previousLocation.Y); newMargin.Right = margin.Right - (currentLocation.X - previousLocation.X); newMargin.Bottom = margin.Bottom - (currentLocation.Y - previousLocation.Y); activeControl.Margin = newMargin; } } void MouseUp(object sender, PointerRoutedEventArgs e) { Debug.WriteLine("PointerReleased"); ((TextBlock)sender).ReleasePointerCapture(e.Pointer); isTracing = false; Window.Current.CoreWindow.PointerCursor = new Windows.UI.Core.CoreCursor(Windows.UI.Core.CoreCursorType.Arrow, 1); }
Thank you in advance.
Gabriele