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

來源:互聯網
上載者:User

實現步驟:

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

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.