C# WinForms - Paint method questions

Tho*_*mas 5 c# onpaint winforms

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? 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);
}
Run Code Online (Sandbox Code Playgroud)

Jef*_*tes 5

建议控件覆盖On...方法而不是订阅自己的事件.

您应该调用base.OnPaint以确保Paint正确触发该方法.

来自MSDN:

OnPaint方法还使派生类能够在不附加委托的情况下处理事件.这是在派生类中处理事件的首选技术.

对继承者的说明
在派生类中重写OnPaint时,请确保调用基类的OnPaint方法,以便已注册的委托接收事件.


Tho*_*mas 5

这并不重要;两者都工作。OnPaint理论上,覆盖可能会稍微快一点,但这并不是任何人都会注意到的区别。Microsoft 建议覆盖,OnPaint但并没有真正推动这一点。

您需要调用,base.OnPaint因为此方法将调用附加到Paint事件的处理程序。