利用鼠标绘图

Posted on 2019-01-18 18:43  努力成长静待花开  阅读(510)  评论(0编辑  收藏  举报

实现效果:

  

知识运用:

  Graphics类的DrawLine方法和MouseEventArgs类的x,y属性

实现代码:

        private void Form1_MouseMove(object sender, MouseEventArgs e)
        {
            if (lastPoint.Equals(Point.Empty))                      //判断绘图开始点是否为空
            {
                lastPoint = new Point(e.X,e.Y);                     //记录鼠标当前位置
            }
            if (onMouseDown)                                        //开始绘图
            {
                graphics = this.CreateGraphics();
                Point currPoint = new Point(e.X, e.Y);              //获取鼠标当前位置
                graphics.DrawLine(new Pen (Color.Black),lastPoint,currPoint);   //绘图
            }
            lastPoint = new Point(e.X,e.Y);                         //更新绘图点
        }

        private void Form1_MouseDown(object sender, MouseEventArgs e)
        {
            onMouseDown = true;                                     //开始绘图标识设为true;
        }

        private void Form1_MouseUp(object sender, MouseEventArgs e)
        {
            onMouseDown = false;                                    //开始绘图标识设为false;
        }