按下鼠标拖动就能拉出虚线框,先看效果图:
![](https://img.laitimes.com/img/__Qf2AjLwojIjJCLyojI0JCLiIXZ05WZD9CX5RXa2Fmcn9CXwczLcVmds92czlGZvwVP9EUTDZ0aRJkSwk0LcxGbpZ2LcBDM08CXlpXazRnbvZ2LcRlMMVDT2EWNvwFdu9mZvwFMRpWT1gGWlZXUYpVd1kmYr50MZV3YyI2cKJDT29GRjBjUIF2LcRHelR3LcJzLctmch1mclRXY39TN4kDN0QjMxIzMwETM3EDMy8CX0Vmbu4GZzNmLn9Gbi1yZtl2Lc9CX6MHc0RHaiojIsJye.jpg)
实现原理:
利用窗体的三个鼠标事件,按下,移动和释放。按下鼠标时,记录按下的坐标,按住移动时根据移动的位置计算长宽,用gid+画虚线框,显示到窗体上。松开鼠标时画一张透明图像清除上面的痕迹,方框消失。
关键代码:
//鼠标按下事件
private void Form1_MouseDown(object sender, MouseEventArgs e)
{
//记录按下位置
basepoint = e.Location;
//按下标志true
m_down = true;
}
//鼠标移动事件
private void Form1_MouseMove(object sender, MouseEventArgs e)
{
//鼠标有按下才绘图
if (m_down)
{
//实例化一个和窗口一样大的位图
i=new Bitmap(this.Width,this.Height);
//创建位图的gdi对象
g = Graphics.FromImage(i);
//创建画笔
p = new Pen(Color.Red, 2.0f);
//指定线条的样式为划线段
p.DashStyle = System.Drawing.Drawing2D.DashStyle.Dash;
//根据当前位置画图,使用math的abs()方法求绝对值
if (e.X < basepoint.X && e.Y < basepoint.Y)
g.DrawRectangle(p, e.X, e.Y, System.Math.Abs(e.X - basepoint.X), System.Math.Abs(e.Y - basepoint.Y));
else if (e.X > basepoint.X && e.Y < basepoint.Y)
g.DrawRectangle(p, basepoint.X, e.Y, System.Math.Abs(e.X - basepoint.X), System.Math.Abs(e.Y - basepoint.Y));
else if (e.X < basepoint.X && e.Y > basepoint.Y)
g.DrawRectangle(p, e.X, basepoint.Y, System.Math.Abs(e.X - basepoint.X), System.Math.Abs(e.Y - basepoint.Y));
else
g.DrawRectangle(p, basepoint.X, basepoint.Y, System.Math.Abs(e.X - basepoint.X), System.Math.Abs(e.Y - basepoint.Y));
//将位图贴到窗口上
this.BackgroundImage = i;
//释放gid和pen资源
g.Dispose();
p.Dispose();
}
}
//鼠标释放事件
private void Form1_MouseUp(object sender, MouseEventArgs e)
{
//清除图像
i = new Bitmap(this.Width, this.Height);
g = Graphics.FromImage(i);
g.Clear(Color.Transparent);
this.BackgroundImage = i;
g.Dispose();
//标志位置低
m_down = false;
}
别忘了开启窗体双缓存,避免闪烁:
this.DoubleBuffered = true;
完整代码:点击下载