ARTICLE

Overriding the OnPaint Method of a Form in GDI+

Posted by Dinesh Beniwal Articles | GDI+ in VB.NET September 28, 2010
In this article you will learn how to Override the OnPaint Method of a Form in GDI+.
 
Reader Level:

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

    Protected Overrides Sub OnPaint(ByVal args As PaintEventArgs)
    'Add your drawing code here
    End Sub

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 Overrides Sub OnPaint(ByVal args As PaintEventArgs)
        'Get the Graphics object from PaintEventArgs
        Dim g As Graphics = 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)
    End Sub

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.

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
Nevron Diagram
Become a Sponsor
PREMIUM SPONSORS
  • Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
    Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
6 Months Free & No Setup Fees ASP.NET Hosting!
Become a Sponsor