C# WinForms - Paint 方法问题

发布于 2024-09-08 05:03:26 字数 346 浏览 9 评论 0原文

我不确定使用图形的最佳方法是什么 - 我应该将我的类附加到主窗体 Paint 事件然后进行绘图,还是最好像这样从覆盖的 OnPaint void 中调用它?我的意思是,这样做可以吗:

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

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

遇到 2024-09-15 05:03:26

建议控件重写 On... 方法,而不是订阅自己的事件。

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

来自 MSDN

OnPaint 方法还可以
派生类来处理事件
无需附加代表。这是
首选处理技术
派生类中的事件。

继承人注意事项
当覆盖时
OnPaint 在派生类中,请务必
调用基类的OnPaint方法
以便注册代表收到
活动。

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.

回忆躺在深渊里 2024-09-15 05:03:26

这其实并不重要;两者都有效。理论上,重写 OnPaint 可能会稍微快一点,但这并不是任何人都会注意到的差异。微软建议重写OnPaint,但并没有真正推动这一点。

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

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文