c-sharp to achieve the mouse box selection effect code

  • 2020-04-01 23:36:50
  • OfStack

Implementation steps:

1. To achieve several events (down, move, up) selected by the entire mouse box, when the mouse click down to record the starting point of the mouse box selection, the mouse lifted the end of the operation.

2. Calculate the 4-point coordinates of the selected rectangle based on the mouse coordinates obtained in the process of mouse frame selection. The 4-point coordinates are arranged in a clockwise direction.

3. Draw the rectangle on the class through the shape-path class.

The code is as follows:


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


Related articles: