C# WinForms - Paint method questions

北城以北 提交于 2019-12-01 18:02:12

问题


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

回答1:


It is recommended that controls override the On... methods rather than subscribe to their own events.

You should call base.OnPaint to ensure the Paint method is fired properly.

From MSDN:

The OnPaint method also enables derived classes to handle the event without attaching a delegate. 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.




回答2:


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. Microsoft recommends overriding OnPaint but doesn't really motivate this.

You need to call base.OnPaint because this method will invoke handlers attached to the Paint event.



来源:https://stackoverflow.com/questions/3195459/c-sharp-winforms-paint-method-questions

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!