替换Paint事件C#

时间:2012-08-22 13:32:53

标签: c# gdi+ nullreferenceexception

我正在使用分层表单,我在Visual Basic .NET中找到了一个很好的例子,但遇到了将源代码转换为C#的问题。 Visual Basic.NET实现使用阴影修饰符有效地替换Form Class' Invalidate()方法,然后对Paint事件执行相同的操作。

  

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

我将代码转换为C#,因此它看起来如下:

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();
    }

但是当调用该方法时,我收到一个 NullReferenceException - 未将对象引用设置为对象的实例。

我也尝试了不同的实现,但收到了同样的例外。

    public delegate void PaintEventHandler(Graphics g);
    public event PaintEventHandler Paint;

有人可以告诉我我做错了什么吗?感谢。

2 个答案:

答案 0 :(得分:1)

您需要在调用事件之前检查null:

if (Paint != null)   
    Paint(this, new PaintEventArgs(g, Rectangle.Empty));

答案 1 :(得分:0)

默认情况下,您的Paint事件不包含任何功能。你需要添加一些才能运行它。

Paint += new PaintEventHandler(Form1_Paint);

我声明:

void Form1_Paint(object sender, PaintEventArgs e)

<小时/> 您应该在程序中执行的操作是调用函数onPaint(),或者更好地将函数添加到Paint事件而不是覆盖它。