经常看到别人拿个四四方方的写字板用笔写字,用C#其实也可以实现,大致思路就是处理鼠标的坐标和Graphics,
代码如下:
首先声明两个全局变量
bool isMouseDown = false; Point point = new Point();
再重写MouseDown事件:
protected override void OnMouseDown(MouseEventArgs e) { point = e.Location; //当前的坐标 isMouseDown = true;//表示已经按下鼠标 }
因为写字的时候少不了上下左右移动,这里还要重写Move事件:
protected override void OnMouseMove(MouseEventArgs e) { if (isMouseDown) { using (Graphics G = this.CreateGraphics()) { G.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias; using (Pen pen=new Pen (Color.Black,3f)) //画笔 { G.DrawLine(pen, point, e.Location);//开始画线 point = e.Location;//更新坐标 } } } }
最后一步,重写MouseUp事件即可:
protected override void OnMouseUp(MouseEventArgs e) { isMouseDown = false; }
效果图如下:初始界面
写字的界面