Saturday, June 6, 2009

How to draw on a Windows Form using C# .NET

1. Create a new Windows Forms Application on Visual Studio
2. In the design mode click on the form
3. On the properties window click on events
4. Double click the "Paint" event

and the final step:

5. Put the code below in the file that opens:

using System;
using System.Drawing;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        private Bitmap DrawingArea;  // Area to draw on.

        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            DrawingArea = new Bitmap(
                    this.ClientRectangle.Width,
                    this.ClientRectangle.Height,
                    System.Drawing.Imaging.PixelFormat.Format32bppArgb);
            using (var canvas = Graphics.FromImage(DrawingArea))
            {
                canvas.Clear(Color.Transparent);
                canvas.FillPolygon(Brushes.Black, new PointF[] { new PointF(10, 10), new PointF(0, 0), new PointF(0, 10) });
            }
            this.Invalidate();
        }

        private void Form1_Paint(object sender, PaintEventArgs e)
        {
            e.Graphics.DrawImage(DrawingArea, 0, 0, DrawingArea.Width, DrawingArea.Height);
        }
    }
}

4 comments:

Quique said...

Hi,

I am doing something like your program. I want to draw manual signatures done by mouse, do you think the better option is painting point to point? and, in that case, is there any method to point a simple point? or otherwise is there another way to do it?

Thanks in advance.

Regards

Jader Dias said...

@Quique

I can't help you. But maybe someone at http://stackoverflow.com/ can.

Quique said...

Thanks!

I got a solution in that web.

Anonymous said...

can you senm the link