110,577
社区成员
发帖
与我相关
我的任务
分享
public partial class Form1 : Form
{
Point startPoint = new Point(-1, -1);
Rectangle lastRect = Rectangle.Empty;
List<Rectangle> rectangles = new List<Rectangle>();
public Form1()
{
InitializeComponent();
}
protected override void OnMouseDown(MouseEventArgs e)
{
this.startPoint = this.PointToScreen(e.Location);
}
protected override void OnMouseMove(MouseEventArgs e)
{
if (this.startPoint.X >= 0)
{
Point current = this.PointToScreen(e.Location);
Size size = new Size(current.X - startPoint.X, current.Y - startPoint.Y);
ControlPaint.DrawReversibleFrame(lastRect, this.BackColor, FrameStyle.Dashed); //擦旧
lastRect = new Rectangle(startPoint, size);
ControlPaint.DrawReversibleFrame(lastRect, this.BackColor, FrameStyle.Dashed); //画新
}
}
protected override void OnMouseUp(MouseEventArgs e)
{
if (this.startPoint.X >= 0)
{
ControlPaint.DrawReversibleFrame(lastRect, this.BackColor, FrameStyle.Dashed); //擦
this.startPoint.X = -1;
this.rectangles.Add(Normalize(this.RectangleToClient(lastRect)));
this.lastRect = Rectangle.Empty;
this.Invalidate();
}
}
protected override void OnPaint(PaintEventArgs e)
{
foreach (Rectangle rect in this.rectangles)
{
e.Graphics.DrawRectangle(Pens.Black, rect);
}
}
private Rectangle Normalize(Rectangle rect)
{
if (rect.Width < 0) { rect.X += rect.Width; rect.Width = -rect.Width; }
if (rect.Height < 0) { rect.Y += rect.Height; rect.Height = -rect.Height; }
return rect;
}
}