c# 鼠标左键绘制矩形
1.鼠标左键按下,记录开始绘图,并记录当前鼠标位置为开始位置
2.鼠标移动,清除之前绘制的图(关键步骤),并将鼠标的位置记录为结束位置
3.鼠标松开,绘图结束
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace 画矩形
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
// 开始点
Point start;
// 是否绘制
bool blnDraw = false;
// 矩形
Rectangle rect = new Rectangle();
private void pictureBox1_MouseDown(object sender, MouseEventArgs e)
{
// 指定开始点
start = e.Location;
blnDraw = true;
}
private void pictureBox1_MouseUp(object sender, MouseEventArgs e)
{
blnDraw &= false;
}
private void pictureBox1_MouseMove(object sender, MouseEventArgs e)
{
if (blnDraw)
{
if (e.Button != MouseButtons.Left)
{
return;
}
// 关键:使本次移动之前所绘制的图像无效
pictureBox1.Invalidate();
// 指定结束点
Point tempEndPoint = e.Location;
rect.Location = new Point(
Math.Min(start.X, tempEndPoint.X),
Math.Min(start.Y, tempEndPoint.Y));
// 指定绘制矩形的尺寸
rect.Size = new Size(
Math.Abs(start.X - tempEndPoint.X),
Math.Abs(start.Y - tempEndPoint.Y));
}
}
private void pictureBox1_Paint(object sender, PaintEventArgs e)
{
if (blnDraw)
{
if (rect != null && rect.Width > 0 && rect.Height > 0)
{
//重新绘制颜色为红色
e.Graphics.DrawRectangle(new Pen(Color.Red, 3), rect);
}
}
}
}
}