Use some dialog to select a colour for left and right mouse buttons and store that in a class level variable i.e.
if (_leftPen != null) { _leftPen.Dispose(); }
_leftPen = new Pen(selectedColour, 1f);
Note that 1f
is the thickness of the Pen
, this can be changed to meet your requirements.
Then in your drawing method just use _leftPen
. Then just apply similar logic for the right mouse button i.e. _rightPen
. You then have:
private Pen _leftPen = Pens.Black;
private Pen _rightPen = Pens.Red;
private void Form1_MouseMove(object sender, MouseEventArgs e)
{
if (e.Button == System.Windows.Forms.MouseButtons.Left)
{
Graphics graphic = this.CreateGraphics();
graphic.DrawLine(_leftPen, e.X, e.Y, e.X + 1, e.Y + 1);
}
if (e.Button == System.Windows.Forms.MouseButtons.Right)
{
Graphics graphic = this.CreateGraphics();
graphic.DrawLine(_rightPen, e.X, e.Y, e.X + 1, e.Y + 1);
}
}
All you need to do is find a way for the user to select their own colour.
Also note the comment by @Taw:
Winforms graphics basic rule #1 : Never use control.CreateGraphics! Never try to cache a Graphics object! Either draw into a Bitmap bmp using a Graphics g = Graphics.FromImage(bmp) or in the Paint event of a control, using the e.Graphics parameter..The system needs to draw all the controls' surfaces at times you can't control; therefore all you want to add to those surfaces must be created from the one event that the system will call, which is the Paint event.
You should use your code in the Paint
event and in the MouseMove
event you should store the positions of the line that you want to draw then update this later.
private Pen _leftPen = Pens.Black;
private Pen _rightPen = Pens.Red;
private List<Point> _leftPoints = new List<Point>();
private List<Point> _rightPoints = new List<Point>();
private void Form1_MouseMove(object sender, MouseEventArgs e)
{
if (e.Button == System.Windows.Forms.MouseButtons.Left)
{
_leftPoints.Add(new Point(e.X, e.Y));
}
if (e.Button == System.Windows.Forms.MouseButtons.Right)
{
_rightPoints.Add(new Point(e.X, e.Y));
}
this.Invalidate();
}
private void Form1_Paint(object sender, PaintEventArgs e)
{
foreach (Point point in _leftPoints)
{
e.Graphics.DrawLine(_leftPen, point.X, point.Y, point.X + 1, point.Y + 1);
}
//Similar code for _rightPoints here
}
Note the call to Invalidate
forces the form to repaint itself. If applicable you may use this.Refresh()
or this.Update()
instead.