//设置默认选中区域 var defaultSelection = new Rectangle(5, 5, 200, 200); makeControlRegionSelectable(pictureBox1, defaultSelection);
void makeControlRegionSelectable(Control control, Rectangle? defaultSelection = null) { var isMouseDown = false; var startPoint = new Point(); var endPoint = new Point(); Point? lastStartPoint = null; Point? lastEndPoint = null; if (defaultSelection != null) { startPoint = defaultSelection.Value.Location; endPoint = new Point(defaultSelection.Value.Left + defaultSelection.Value.Width, defaultSelection.Value.Top + defaultSelection.Value.Height); } Action<Point,Point> DrawRectangle = delegate (Point start, Point end) { Graphics g1 = pictureBox1.CreateGraphics(); g1.Clear(Color.White); g1.DrawRectangle(new Pen(Color.Green, 1) { DashStyle = System.Drawing.Drawing2D.DashStyle.Dash }, new Rectangle(start.X, start.Y, end.X - start.X, end.Y - start.Y)); }; control.MouseDown += delegate (object sender, MouseEventArgs e) { lastStartPoint = startPoint; lastEndPoint = endPoint; startPoint = e.Location; endPoint = startPoint; isMouseDown = true; control.Capture = true; }; control.MouseUp += delegate (object sender, MouseEventArgs e) { isMouseDown = false; control.Capture = false; var minMove = 20; //设置选中精度 if (e.Location.X - startPoint.X < minMove && e.Location.Y - startPoint.Y < minMove) { if(lastStartPoint != null && lastEndPoint != null) { startPoint = lastStartPoint.Value; endPoint = lastEndPoint.Value; return; } } endPoint = e.Location; }; control.MouseMove += delegate (object sender, MouseEventArgs e) { if (isMouseDown) DrawRectangle(startPoint, e.Location); }; //自动重绘 var timer = new Timer(); timer.Interval = 100; timer.Tick += delegate (object sender, EventArgs e) { if (isMouseDown) return; if(endPoint != null) DrawRectangle(startPoint, endPoint); }; timer.Start(); }
标签:endPoint,C#,null,Value,选中,new,winform,startPoint,defaultSelection From: https://www.cnblogs.com/nanfei/p/16982092.html