I’m working with layered forms and I found a great example in Visual Basic .NET but came across a problem converting the source to C#. The Visual Basic.NET implementation uses the shadows modifier to effectively replace the Form Class’ Invalidate() method and then does the same for the Paint event.
Public Shadows Event Paint(ByVal G As Drawing.Graphics)
Public Shadows Sub Invalidate()
Dim B As New Drawing.Bitmap(ClientSize.Width, ClientSize.Height)
Dim G As Drawing.Graphics = Drawing.Graphics.FromImage(B) : G.SmoothingMode = Drawing.Drawing2D.SmoothingMode.AntiAlias
RaiseEvent Paint(G)
G.Dispose()
SetBits(B)
B.Dispose()
End Sub
I converted the code to C# so it looks like the following:
public new event PaintEventHandler Paint;
public new void Invalidate()
{
Bitmap b = new Bitmap(ClientSize.Width, ClientSize.Height);
Graphics g = Graphics.FromImage(b);
g.SmoothingMode = SmoothingMode.AntiAlias;
Paint(this, new PaintEventArgs(g, Rectangle.Empty));
g.Dispose();
SetBits(b);
b.Dispose();
}
But when the method is invoked I receive a NullReferenceException – Object reference not set to an instance of an object.
I also tried a different implementation, but received the same exception.
public delegate void PaintEventHandler(Graphics g);
public event PaintEventHandler Paint;
Could somebody tell me what I’m doing wrong? Thanks.
You need to check for null before invoking the event: