WPF拖动绘制

WPF研究 专栏收录该内容
114 篇文章 3 订阅

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;
        }
    }
}

  • 1
    点赞
  • 0
    评论
  • 0
    收藏
  • 一键三连
    一键三连
  • 扫一扫,分享海报

©️2021 CSDN 皮肤主题: 成长之路 设计师:Amelia_0503 返回首页
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、C币套餐、付费专栏及课程。

余额充值