服务器之家

服务器之家 > 正文

用C# 实现鼠标框选效果的实现代码

时间:2020-11-30 15:35     来源/作者:C#教程网

实现步骤:

1.实现整个鼠标框选的几个事件(down、move、up),当鼠标点下记录鼠标框选的起点,鼠标抬起结束操作。

2.以鼠标框选过程中获取的鼠标坐标为基点计算框选的矩形的4点坐标,4点坐标以顺时针方向布点。

3.通过Shape.Path类实现在类上画出此矩形。

代码如下:

复制代码 代码如下:


namespace HostDemo {
 public class HostCanvas : Canvas {
  public HostCanvas() {
   InitializeComponent();
  }

 

  private void InitializeComponent() {
   this.Loaded += OnLoad;
   this.MouseDown += OnMouseDown;
   this.MouseMove += OnMouseMove;
   this.MouseUp += OnMouseUp;
   locus = new Path();
   locus.Fill = new SolidColorBrush(Color.FromArgb(1, 255, 255, 255));
   locus.Stroke = Brushes.Red;
   locus.StrokeThickness = 1;
   locus.IsManipulationEnabled = true;
  }

  void OnMouseUp(object sender, System.Windows.Input.MouseButtonEventArgs e) {
   ispath = false;
  }

  void OnMouseMove(object sender, System.Windows.Input.MouseEventArgs e) {
   if(ispath){
    endpoint = e.GetPosition(this);
    locus.Data = DrawingRect(startpoint,endpoint);
   }
  }

  void OnMouseDown(object sender, System.Windows.Input.MouseButtonEventArgs e) {
   if(!this.Children.Contains(locus)) this.Children.Add(locus);
   if (locus.Data != null) locus.Data = null;
   startpoint = e.GetPosition(this);
   ispath = true;
  }

  void OnLoad(object sender, System.Windows.RoutedEventArgs e) {
   this.Background = new SolidColorBrush(Color.FromArgb(35, 255, 255, 255));
  }

  private PathGeometry DrawingRect(Point beginpoint, Point closepoint) {
   PathGeometry result = new PathGeometry(); 
   PathFigure figure = new PathFigure();
   figure.IsClosed = true;
   figure.StartPoint = beginpoint;
   PathSegmentCollection pathSegmentCollection = new PathSegmentCollection();
   PathFigureCollection pathFigureCollection = new PathFigureCollection();  
   LineSegment m1 = new LineSegment();
   m1.Point = new Point(closepoint.X, beginpoint.Y);
   LineSegment m2 = new LineSegment();
   m2.Point = closepoint;
   LineSegment m3 = new LineSegment();
   m3.Point = new Point(beginpoint.X, closepoint.Y);
   pathSegmentCollection.Add(m1);
   pathSegmentCollection.Add(m2);
   pathSegmentCollection.Add(m3);
   figure.Segments = pathSegmentCollection;
   pathFigureCollection.Add(figure);
   result.Figures = pathFigureCollection;

   return result();
  }

  private Path locus;
  private bool ispath = false;
  private Point startpoint;
  private Point endpoint;
 }
}

标签:

相关文章

热门资讯

2020微信伤感网名听哭了 让对方看到心疼的伤感网名大全
2020微信伤感网名听哭了 让对方看到心疼的伤感网名大全 2019-12-26
Intellij idea2020永久破解,亲测可用!!!
Intellij idea2020永久破解,亲测可用!!! 2020-07-29
歪歪漫画vip账号共享2020_yy漫画免费账号密码共享
歪歪漫画vip账号共享2020_yy漫画免费账号密码共享 2020-04-07
电视剧《琉璃》全集在线观看 琉璃美人煞1-59集免费观看地址
电视剧《琉璃》全集在线观看 琉璃美人煞1-59集免费观看地址 2020-08-12
最新idea2020注册码永久激活(激活到2100年)
最新idea2020注册码永久激活(激活到2100年) 2020-07-29
返回顶部