SIGN UP MEMBER LOGIN:    
ARTICLE

Overriding the OnPaint Method of a Form in GDI+

Posted by Dinesh Beniwal Articles | GDI+ & Graphics July 02, 2010
In this article you will learn how to Override the OnPaint Method of a Form in GDI+.
Reader Level:
Download Files:
 

This article has been excerpted from book "GraphicsProgramming with GDI+".

We have already seen this in previous articles. We can override the onPaint method by defining it as follows:

Protected override void OnPaint (PaintEventArgs args)
{
//Add your drawing code here
}

Then we can use the Graphics property of PaintEventArgs to draw, lines, shapes, text, and images. Listing 13.4 draws a few graphics shapes and text on our form's OnPaint method. To test this code, create a Windows application and add the code to it.

LISTING 13.4: Using OnPaint to draw

        protected override void OnPaint(PaintEventArgs args)
        {
            //Get the Graphics object from PaintEventArgs
            Graphics g = args.Graphics;
            //Draw rectangle
            g.DrawRectangle(
            new Pen(Color.Blue, 3),
            new Rectangle(10, 10, 50, 50));
            //Fill ellipse
            g.FillEllipse(
            Brushes.Red,
            new Rectangle(60, 60, 100, 100));
            //Draw text
            g.DrawString("Text",
            new Font("Verdana", 14),
            new SolidBrush(
Color.Green),
            200, 200);
        }

Using Visual Studio .NET to add the Paint Event Handler

If you are using Visual Studio .NET, the easiest way to add a paint event handler is to use the Properties windows of a form or control ad add a paint event handler.

Disposing of Graphics Objects

It is usually good programming practice to dispose of objects when you're finished using them. But it may not always be the best practice. A Graphics object must always be disposed of it was created via the CreateGraphics method or other "CreateFrom" methods. If we use a Graphics object on a paint event or the OnPaint method from the PaintEventArgs.Graphics property, we do not have to dispose of it.

NOTE

Do not dispose of Graphics objects associated with Windows controls such as Button, ListBox, or DataGrid.

If you create objects such as pens and brushes, always dispose of them. Although it is acceptable practice to rely on the garbage collector, doing so may often be at the expense of application performance. Garbage collection can be a costly affair because the garbage collector checks the memory for objects that haven't been disposed of, and this process absorbs processor time. However, the Dispose method of an object tells the garbage collector that the object is finished and ready to be disposed of. Calling the Dispose method eliminates the need to have the garbage collector check memory and thus saves processor time.

In Web pages, it is always food practice to dispose of objects as soon as they are done being used.

The OnPaintBackground Method

The OnPaintBackground method paints the background of a control. This method is usually overridden in the derived classes to handle the event without attaching a delegate. Calling the OnPaintBackground method calls OnPaintBackground of the base automatically, so we do not need to call it explicitly.
 
book.gif

Login to add your contents and source code to this article
share this article :
post comment
 

Hi :-)
Excuse me for my funny question and sending such big code.
I am draw some graphs which is time consuming to draw. it needs to send each point to the function and after caculation set a pixel. after that range of the function passed we have the graph and there is no problem.
in this code that I am sending you use SetPixel function. I use the way that you mentioned and my way -call WndProc(...) - but both have same result. when you get the form by your mouse and hold the left click on the the title bar of the form and move it in the screen it is ok. but!!! but if you move the form in a way which a part of the form go out of screen the function is called and when it is time consuming it want do the whole operation from begining to end to draw the area. is there any way to solve this problem?
thanks.

using System;

using System.Collections.Generic;

using System.ComponentModel;

using System.Data;

using System.Drawing;

using System.Linq;

using System.Text;

using System.Windows.Forms;

using System.Runtime.InteropServices;

namespace WindowsFormsApplication1

{

public partial class Form1 : Form

{

[DllImport("user32.dll")]

static extern IntPtr GetDC(IntPtr hWnd);

[DllImport("user32.dll")]

static extern int ReleaseDC(IntPtr hWnd, IntPtr hDC);

[DllImport("gdi32.dll")]

static extern int GetPixel(IntPtr hDC, int x, int y);

[DllImport("gdi32.dll")]

static extern int SetPixel(IntPtr hDC, int x, int y, int color);

static public Color GetPixel(Control control, int x, int y)

{

Color color = Color.Empty;

if (control != null)

{

IntPtr hDC = GetDC(control.Handle);

int colorRef = GetPixel(hDC, x, y);

color = Color.FromArgb(

(int)(colorRef & 0x000000FF),

(int)(colorRef & 0x0000FF00) >> 8,

(int)(colorRef & 0x00FF0000) >> 16);

ReleaseDC(control.Handle, hDC);

}

return color;

}

static public void SetPixel(Control control, int x, int y, Color color)

{

if (control != null)

{

IntPtr hDC = GetDC(control.Handle);

int argb = color.ToArgb();

int colorRef =

(int)((argb & 0x00FF0000) >> 16) |

(int)(argb & 0x0000FF00) |

(int)((argb & 0x000000FF) << 16);

SetPixel(hDC, x, y, colorRef);

ReleaseDC(control.Handle, hDC);

}

}

public Form1()

{

InitializeComponent();

}

protected override void OnPaint(PaintEventArgs args)

{

for (int i = 0; i < 100; i++)

for (int j = 0; j < 100; j++)

SetPixel(this, i + 10, 10 + j, Color.Red);

for (int i = 0; i < 100; i++)

for (int j = 0; j < 100; j++)

SetPixel(this, i + 10, 10 + j, Color.Blue);

}

}

}

Posted by loghman dastgheyb Nov 10, 2010
6 Months Free & No Setup Fees ASP.NET Hosting!
Become a Sponsor
PREMIUM SPONSORS
  • Get 2 Months Free of ASP.NET Hosting for Only $4.95/month! Receive FREE MS SQL and MySQL Databases Including ASP.NET 4/3.5, MVC 3.0, Silverlight 4, Windows 2008/IIS 7.0 Plus FREE IIS 7 Modules. Host UNLIMITED ASP.NET Web Sites - Click Here!
    ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications. Visit DynamicPDF here
Become a Sponsor