简体   繁体   English

替换绘画事件C#

[英]Replace Paint Event C#

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#. 我正在使用分层表单,并且在Visual Basic .NET中找到了一个很好的示例,但是遇到了将源转换为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. Visual Basic.NET实现使用shadows修饰符有效地替换Form类的Invalidate()方法,然后对Paint事件执行相同的操作。

Public Shadows Event Paint(ByVal G As Drawing.Graphics) Public Shadows Event Paint(ByVal G作为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: 我将代码转换为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();
    }

But when the method is invoked I receive a NullReferenceException - Object reference not set to an instance of an object. 但是,当调用该方法时,我收到一个NullReferenceException-未将对象引用设置为对象的实例。

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: 您需要在调用事件之前检查null:

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

by default, your Paint event dose not contain any functions. 默认情况下, Paint事件不包含任何功能。 you well need to add a few in order to run this. 您需要添加一些才能运行此程序。

Paint += new PaintEventHandler(Form1_Paint);

where i declare: 我在哪里声明:

void Form1_Paint(object sender, PaintEventArgs e)


what you should do in your program is to call the function onPaint() or, better, to add your function to the Paint event instead of overriding it. 在程序中应该做的是调用函数onPaint()或者更好的方法是将函数添加到Paint事件中,而不是重写它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM