public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
//Add EventHandlers
this.
pictureBox1.
MouseDown +=
new MouseEventHandler
(this.
PictureBox1_MouseDown);
this.
pictureBox1.
MouseUp +=
new MouseEventHandler
(this.
PictureBox1_MouseUp);
this.
pictureBox1.
Paint +=
new PaintEventHandler
(this.
PictureBox1_Paint);
}
//The lines that have been drawn but not saved.
private List<Line> lines =
new List<Line>
();
//The start point of the line currently being drawn.
private Point start;
private void Form1_Load(object sender, EventArgs e)
{
//Place a blank image in the PictureBox control.
this.
pictureBox1.
Image =
new Bitmap
(this.
pictureBox1.
Width,
this.
pictureBox1.
Height);
}
private void PictureBox1_MouseDown(object sender, System.Windows.Forms.MouseEventArgs e)
{
//Remember the point at which the line started.
this.start = e.Location;
}
private void PictureBox1_MouseUp(object sender, System.Windows.Forms.MouseEventArgs e)
{
//Remember the point at which the line ended.
Point end = e.Location;
//Add the new line to the list.
this.
lines.
Add(new Line
(this.
start, end
));
Rectangle area =
new Rectangle
(Math.
Min(this.
start.
X, end.
X),
Math.Min(this.start.Y, end.Y),
Math.Abs(this.start.X - end.X),
Math.Abs(this.start.Y - end.Y));
//Inflate the rectangle by 1 pixel in each direction to ensure every changed pixel will be redrawn.
area.Inflate(1, 1);
//Force the control to repaint so the new line is drawn.
this.pictureBox1.Invalidate(area);
this.pictureBox1.Update();
}
private void PictureBox1_Paint(object sender, System.Windows.Forms.PaintEventArgs e)
{
//Draw each line on the control.
this.DrawLines(e.Graphics);
}
private void Save()
{
//Create a Graphics object from the Image in the PictureBox.
using (Graphics g = Graphics.FromImage(this.pictureBox1.Image))
{
//Draw each line on the image to make them permanent.
this.DrawLines(g);
}
//Clear the temporary lines that were just saved.
this.Clear();
}
private void Clear()
{
//Clear all unsaved lines.
this.lines.Clear();
//Force the control to repaint so the lines are removed.
this.pictureBox1.Refresh();
}
private void DrawLines(Graphics g)
{
foreach (Line line in this.lines)
{
g.DrawLine(Pens.Black, line.start, line.end);
}
}
}
public class Line
{
//The line's start point.
public Point start
{
get { return _start; }
set { _start = value; }
}
//The line's end point.
public Point end
{
get { return _end; }
set { _end = value; }
}
public Line() : this(Point.Empty, Point.Empty)
{
}
public Line(Point start, Point end)
{
this._end = end;
this._start = start;
}
private Point _start;
private Point _end;
}