⚠️ Warning: This website is still being developed. Code examples, videos, and links may be broken while I continue to work on it. -- Scott, May 10, 2020
Resources for visualizing data using C# and the .NET platform

Simple Paint with C

This article describes how to create a simple MSPaint-like drawing program with C# using System.Drawing.

Code

Most articles on this website have described how to render to a Bitmap in memory then display it in a Picturebox.

This example will instead draw directly on a Panel control, using Panel.CreateGraphics() to obtain Graphics we will draw on.

Color Selector

A button will launch a ColorDialog to let the user select a custom color. The color will be applied to the background of the button as a form of storage so it can be recalled later.

private void btnColor_Click(object sender, EventArgs e)
{
    using (var diag = new ColorDialog())
        if (diag.ShowDialog() == DialogResult.OK)
            btnColor.BackColor = diag.Color;
}

Clear Button

private void btnClear_Click(object sender, EventArgs e)
{
    using (var gfx = panel1.CreateGraphics())
        gfx.Clear(Color.Black);
}

Mouse Tracking

These methods are triggered by mouse events. The current and previous mouse locations are stored in two Point variables at the class level.

Point mouseLocA;
Point mouseLocB;

private void panel1_MouseDown(object sender, MouseEventArgs e)
{
    mouseLocA = e.Location;
    mouseLocB = e.Location;
    DrawMouseLine();
}

private void panel1_MouseMove(object sender, MouseEventArgs e)
{
    if (e.Button == MouseButtons.Left)
    {
        mouseLocA = mouseLocB;
        mouseLocB = e.Location;
        DrawMouseLine();
    }
}

Drawing Lines

This method draws a line between the two mouse points.

  • Graphics.SmoothingMode is set to configure anti-aliasing
  • StartCap and EndCap are set to Round to avoid rectangular edges
private void DrawMouseLine()
{
    using (var pen = new Pen(btnColor.BackColor, (int)nudSize.Value))
    using (var gfx = panel1.CreateGraphics())
    {
        gfx.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
        pen.StartCap = System.Drawing.Drawing2D.LineCap.Round;
        pen.EndCap = System.Drawing.Drawing2D.LineCap.Round;
        gfx.DrawLine(pen, mouseLocA, mouseLocB);
    }
}

Source Code

/examples/drawing/simple-paint/SimplePaint