Overriding the Paint Event
The basic steps for overriding any event defined in the .NET Framework are identical and are summarized in the following list.
To override an inherited event
- Override the protected OnEventName method.
- Call the OnEventName method ** of the base class from the overridden OnEventName method, so that registered delegates receive the event.
The Paint event is discussed in detail here because every Windows Forms control must override the Paint event that it inherits from Control. The base Control class does not know how a derived control needs to be drawn and does not provide any painting logic in the OnPaint method. The OnPaint method of Control simply dispatches the Paint event to registered event receivers.
If you worked through the sample in Developing a Simple Windows Forms Control, you have seen an example of overriding the OnPaint method. The following code fragment is taken from that sample.
Public Class FirstControl
Inherits Control
Public Sub New()
End Sub
Protected Overrides Sub OnPaint(e As PaintEventArgs)
' Call the OnPaint method of the base class.
MyBase.OnPaint(e)
' Call methods of the System.Drawing.Graphics object.
e.Graphics.DrawString(Text, Font, New SolidBrush(ForeColor), RectangleF.op_Implicit(ClientRectangle))
End Sub
End Class
[C#]
public class FirstControl : Control{
public FirstControl() {}
protected override void OnPaint(PaintEventArgs e) {
// Call the OnPaint method of the base class.
base.OnPaint(e);
// Call methods of the System.Drawing.Graphics object.
e.Graphics.DrawString(Text, Font, new SolidBrush(ForeColor), ClientRectangle);
}
}
The PaintEventArgs class contains data for the Paint event. It has two properties, as shown in the following code.
Public Class PaintEventArgs
Inherits EventArgs
...
Public ReadOnly Property ClipRectangle() As System.Drawing.Rectangle
...
End Property
Public ReadOnly Property Graphics() As System.Drawing.Graphics
...
End Property
...
End Class
[C#]
public class PaintEventArgs : EventArgs {
...
public System.Drawing.Rectangle ClipRectangle {...}
public System.Drawing.Graphics Graphics {...}
...
}
ClipRectangle is the rectangle to be painted, and the Graphics property refers to a System.Drawing.Graphics object. The classes in the System.Drawing namespace are managed classes that provide access to the functionality of GDI+, the new Windows graphics library. The Graphics object has methods to draw points, strings, lines, arcs, ellipses, and many other shapes.
A control invokes its OnPaint method whenever it needs to change its visual display. This method in turn raises the Paint event.
See Also
Handling and Raising Events | Rendering a Windows Forms Control | Defining an Event