程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> C語言 >> C >> C語言基礎知識 >> 用C# 實現鼠標框選效果的實現代碼

用C# 實現鼠標框選效果的實現代碼

編輯: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;
 }
}

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved