用鼠标在窗体中画线
(作者:张均洪)
我们先在同一命名空中定义一个类和一个接口:
using System; using System.Collections.Generic; using System.Text; using System.Runtime.Serialization; using System.Runtime.Serialization.Formatters; using System.Runtime.Serialization.Formatters.Binary;
public interface Ishape { void Draw(Graphics g); } //这个类提供画线的方法 [Serializable] public class Line : Ishape { Point startP, endP; public Line(Point sp, Point ep) { this.startP = sp; this.endP = ep; } public void Draw(Graphics g) { g.DrawLine(Pens.Black, startP, endP); } }
新建一个窗体:FORM1
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Windows.Forms; using System.IO; using System.Runtime.Serialization; using System.Collections;
//定义窗体级公用变量
//开始画线的起点坐标,此变量的值将在MOUSEDOWN事件中确定 Point startPoint; //定义一个ARRAYLIST,用于存储对象 private ArrayList shapes=new ArrayList();
protected override void OnPaint(PaintEventArgs e) { Graphics g = e.Graphics; //GETENUMERATOR返回枚举数对象,这个对象为类 IEnumerator shapeEnum = shapes.GetEnumerator(); //WHILE是查找出合适的类,并利用其DRAW方法 while (shapeEnum.MoveNext()) { Ishape shape = (Ishape)shapeEnum.Current; //运用相关类的DRAW方法, //当我们前面定义多个方法时很有用,比例我们还可以加些 //画矩形(DrawRectangle)画园(DrawEllipse)等 //在这里我们只定义一个方法(画线)。
shape.Draw(g); } }
private void Form1_MouseDown(object sender, MouseEventArgs e) { if (e.Button ==System.Windows.Forms.MouseButtons.Left) { //鼠标按下确定起点的坐标,把这个变量赋于STARTPOINT值 startPoint = new Point(e.X, e.Y); } }
private void Form1_MouseUp(object sender, MouseEventArgs e) { Point endpp = new Point(e.X, e.Y); if (e.Button ==System.Windows.Forms.MouseButtons.Left) { //把LINE类添加到定义好的ARRARYLIST中,以便 //ONPAINT事件处理。 shapes.Add(new Line(startPoint, endpp)); } //这句很关键,没有这句你无法看见你的画的线。 //ONPAINT事件,是在窗体在激活,改变大小,加载,刷新的时候 //才能进行,所以当我们的动作完成后,必须对窗体进行 //刷新操作。 this.Refresh(); }
在新建窗体后注意把窗体背景设为白色喔!! 
|