当我使用 CreateSolidBrush 作为 SetClassLongPtr(hwnd, GCLP_HBRBACKGROUND,
我通过在红色和橙色之间波动背景颜色来模仿爆炸。
使用 SetClassLongPtr(hwnd, GCLP_HBRBACKGROUND, (LONG) CreateSolidBrush( RGB(255, 0, 0) ) ) 后是否必须使用 DeleteObject 或以某种方式释放对象?
void ExplosionVisuals(HWND hwnd)
{
for (int i = 0; i < 10; ++i)
{
SetClassLongPtr(hwnd, GCLP_HBRBACKGROUND, (LONG) CreateSolidBrush( RGB(255, 0, 0) ) ); // Red
InvalidateRect(hwnd, NULL, true);
UpdateWindow(hwnd);
Sleep(100);
SetClassLongPtr(hwnd, GCLP_HBRBACKGROUND, (LONG) CreateSolidBrush( RGB(255, 153, 0) ) ); // Orange
InvalidateRect(hwnd, NULL, true);
UpdateWindow(hwnd);
Sleep(100);
}
SetClassLongPtr(hwnd, GCLP_HBRBACKGROUND, (LONG) GetStockObject(WHITE_BRUSH) );
InvalidateRect(hwnd, NULL, true);
UpdateWindow(hwnd);
return;
}
I'm making a lame imitation of an explosion by fluctuating the background color between red and orange.
Do I have to use DeleteObject or free the object somehow after using SetClassLongPtr(hwnd, GCLP_HBRBACKGROUND, (LONG) CreateSolidBrush( RGB(255, 0, 0) ) ) ?
void ExplosionVisuals(HWND hwnd)
{
for (int i = 0; i < 10; ++i)
{
SetClassLongPtr(hwnd, GCLP_HBRBACKGROUND, (LONG) CreateSolidBrush( RGB(255, 0, 0) ) ); // Red
InvalidateRect(hwnd, NULL, true);
UpdateWindow(hwnd);
Sleep(100);
SetClassLongPtr(hwnd, GCLP_HBRBACKGROUND, (LONG) CreateSolidBrush( RGB(255, 153, 0) ) ); // Orange
InvalidateRect(hwnd, NULL, true);
UpdateWindow(hwnd);
Sleep(100);
}
SetClassLongPtr(hwnd, GCLP_HBRBACKGROUND, (LONG) GetStockObject(WHITE_BRUSH) );
InvalidateRect(hwnd, NULL, true);
UpdateWindow(hwnd);
return;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这段代码泄露了刷子。如果您确实希望每次循环都创建新的画笔,那么您必须获取先前的值(由
SetClassLongPtr
返回)并处理它。更好的方法是创建两个与应用程序具有相同生命周期的画笔。如此频繁地创建新画笔是浪费的。通过这种方法,您可以在关机时处理电刷。
至于动画的实际实现,正如您所承认的,您的代码相当糟糕。
睡眠
很少能解决任何问题,而且这里肯定不存在。如果你有一个计时器会更好。正如 Hans 正确指出的那样,您应该处理 WM_ERASEBKGND 来设置背景画笔。一旦切换到计时器,就不需要调用 UpdateWindow。This code leaks brushes. If you really wish to create new brushes each time round the loop then you have to get the previous value (returned by
SetClassLongPtr
) and dispose of it.A much better approach would be to create two brushes that have the same lifetime as the application. It's wasteful to be creating new brushes so frequently. With this approach you would dispose of the brushes at shutdown.
As to the actual implementation of animation, your code is, as you admit, rather poor.
Sleep
is very seldom the solution to any problem and it certainly isn't here. You would be better off with a timer. And as Hans correctly points out, you should handleWM_ERASEBKGND
to set the background brush. Once you switch to a timer then you don't need to call UpdateWindow.