WPF拖动绘制
using System; using System.Windows; using System.Windows.Controls; using System.Windows.Input; using System.Windows.Shapes; using System.Windows.Media; namespace BrawDraw.Com.HandleAnEvent { class HandleAnEvent { [STAThread] public static void Main() { Application app = new Application(); Window win = new Window(); win.Title = "Handle An Event"; win.MouseDown += WindowOnMouseDown; win.MouseMove += WindowOnMouseMove; win.MouseUp += WindowOnMouseUp; app.Run(win); } static Point startPoint; static Point endPoint; static bool isCapture = false; static void WindowOnMouseDown(object sender, MouseButtonEventArgs args) { Window win = sender as Window; startPoint = args.GetPosition(win); isCapture = true; } static void WindowOnMouseMove(object sender, MouseEventArgs args) { endPoint = args.GetPosition(sender as Window); if (isCapture) { DrawRectangle(sender); //这里隐藏与不隐藏时差别很大,特别是鼠标的最后位置与开始位置的相对位移为负时,特征更加明显。 } } static void WindowOnMouseUp(object sender, MouseButtonEventArgs args) { isCapture = false; DrawRectangle(sender); } static void DrawRectangle(object sender) { #region DoStartEndPointPlace Point tmpPoint = startPoint; if (endPoint.X < startPoint.X) { startPoint.X = endPoint.X; endPoint.X = tmpPoint.X; } if (endPoint.Y < startPoint.Y) { startPoint.Y = endPoint.Y; endPoint.Y = tmpPoint.Y; } #endregion DoStartEndPointPlace Window win = sender as Window; Rectangle rect = new Rectangle(); rect.Stroke = Brushes.Black; rect.Fill = Brushes.SkyBlue; rect.HorizontalAlignment = HorizontalAlignment.Left; rect.VerticalAlignment = VerticalAlignment.Center; rect.Height = Math.Abs(endPoint.Y - startPoint.Y); rect.Width = Math.Abs(endPoint.X - startPoint.X); Canvas canvas = new Canvas(); Canvas.SetLeft(rect, startPoint.X); Canvas.SetTop(rect, startPoint.Y); canvas.Children.Add(rect); win.Content = canvas; } } }