简体   繁体   English

C#WinForms - 绘制方法问题

[英]C# WinForms - Paint method questions

I am not sure what is the best way of using graphics - should I attach my classes to main form Paint event and then do the drawing, or it is better to call it from overidden OnPaint void like this? 我不确定使用图形的最佳方法是什么 - 我应该将我的类附加到主窗体Paint事件然后进行绘图,还是最好从覆盖的OnPaint中调用它像这样? I mean, is it OK to do that like this: 我的意思是,这样做是否可以:

protected override void OnPaint(PaintEventArgs e)
{
    base.OnPaint(e)  //what is this good for? My app works without it as well
    Graphics g=e.Graphics;
    DrawEnemies(g);
    UpdateHUD(g);
    DrawSelectedUnit(g);
}

It is recommended that controls override the On... methods rather than subscribe to their own events. 建议控件覆盖On...方法,而不是订阅自己的事件。

You should call base.OnPaint to ensure the Paint method is fired properly. 您应该调用base.OnPaint以确保正确触发Paint方法。

From MSDN : 来自MSDN

The OnPaint method also enables derived classes to handle the event without attaching a delegate. OnPaint方法还使派生类能够在不附加委托的情况下处理事件。 This is the preferred technique for handling the event in a derived class. 这是在派生类中处理事件的首选技术。

Notes to Inheritors 对继承者的说明
When overriding OnPaint in a derived class, be sure to call the base class's OnPaint method so that registered delegates receive the event. 在派生类中重写OnPaint时,请务必调用基类的OnPaint方法,以便已注册的委托接收事件。

It doesn't really matter; 这并不重要; both work. 都工作。 Overriding OnPaint might be ever so slightly faster in theory, but it's not a difference that anyone will notice. 从理论上讲,重写OnPaint速度可能会略微提高,但任何人都不会注意到这一点。 Microsoft recommends overriding OnPaint but doesn't really motivate this. Microsoft建议覆盖OnPaint但并不能真正激发这一点。

You need to call base.OnPaint because this method will invoke handlers attached to the Paint event. 您需要调用base.OnPaint因为此方法将调用附加到Paint事件的处理程序。

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

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