C#,winform,gdi+,简单实现鼠标拉出虚线框,适合新手

按下鼠标拖动就能拉出虚线框,先看效果图:


实现原理:

利用窗体的三个鼠标事件,按下,移动和释放。按下鼠标时,记录按下的坐标,按住移动时根据移动的位置计算长宽,用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;

完整代码:点击下载

展开阅读全文

没有更多推荐了,返回首页