用C# 实现鼠标框选效果的实现代码
2019/7/10 23:28:26
本文主要是介绍用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;
}
}
这篇关于用C# 实现鼠标框选效果的实现代码的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-11-23增量更新怎么做?-icode9专业技术文章分享
- 2024-11-23压缩包加密方案有哪些?-icode9专业技术文章分享
- 2024-11-23用shell怎么写一个开机时自动同步远程仓库的代码?-icode9专业技术文章分享
- 2024-11-23webman可以同步自己的仓库吗?-icode9专业技术文章分享
- 2024-11-23在 Webman 中怎么判断是否有某命令进程正在运行?-icode9专业技术文章分享
- 2024-11-23如何重置new Swiper?-icode9专业技术文章分享
- 2024-11-23oss直传有什么好处?-icode9专业技术文章分享
- 2024-11-23如何将oss直传封装成一个组件在其他页面调用时都可以使用?-icode9专业技术文章分享
- 2024-11-23怎么使用laravel 11在代码里获取路由列表?-icode9专业技术文章分享
- 2024-11-22怎么实现ansible playbook 备份代码中命名包含时间戳功能?-icode9专业技术文章分享