效果展示
需要三个鼠标的时间来配合
//定义全局变量
int x;
int y;
bool isMouthDown = false;
int width;
int height;
Graphics g;
// 给窗体 加 鼠标点击 MouseDown 事件
private void Form2_MouseDown(object sender, MouseEventArgs e)//MouseEventArgs 获取鼠标位置
{
x = e.X;
y = e.Y;
// true 开始
isMouthDown = true;
}
//给窗体 加 鼠标移动 MouseMove事件
private void Form2_MouseMove(object sender, MouseEventArgs e)
{
if (isMouthDown)
{
width = Math.Abs(e.X - x);
height = Math.Abs(e.Y - y);
//创建类似画板
g = CreateGraphics();
g.Clear(BackColor);
g.FillRectangle(Brushes.CornflowerBlue, //颜色
x < MousePosition.X ? x : e.X,
y < MousePosition.Y ? y : e.Y,
width, height);
}
}
//给窗体 加 鼠标松开 MouseUp事件
private void Form2_MouseUp(object sender, MouseEventArgs e)
{
width = Math.Abs(e.X - x);
height = Math.Abs(e.Y - y);
//创建类似画板
g = CreateGraphics();
g.Clear(BackColor);
g.FillRectangle(Brushes.CornflowerBlue, //颜色
x < MousePosition.X ? x : e.X,
y < MousePosition.Y ? y : e.Y,
width, height);
isMouthDown = false;
}