如何正确释放GDI资源?

How to free GDI resources correctly?

我正在尝试了解如何正确释放 GDI 资源,这是我在阅读许多 GDI 教程后认为的做法:

假设我创建了一个内存 DC,并创建并选择了许多 GDI 对象(HPENHBRUSHHBITMAP 等)放入其中。现在要释放 GDI 资源,我将执行以下操作:

  1. Select 将所有旧的 GDI 对象放入内存 DC(因此 选择所有新创建的 GDI 对象)。
  2. 删除新创建的 GDI 对象。
  3. 删除内存DC

注意第二步和第三步可以倒序进行。即内存DC被删除为GDI对象。

如果我使用的是普通 DC(我使用 GetDC()BeginPaint()),我会用释放它来代替删除 DC。

我做对了吗,还是我漏掉了什么?

  1. Select all of the old GDI object into the memory DC (and hence selecting out all of the newly created GDI objects).
  2. Delete the newly created GDI objects.
  3. Delete the memory DC.

Note that the second and third steps can be performed in reverse order. That is the memory DC is deleted for the GDI objects are.

Did I get this right?

是的,你做到了。

And if I am working with a normal DC (that I got using GetDC() or BeginPaint()), I would replace deleting the DC with just releasing it.

那么,GetDC 将与 ReleaseDC 匹配,而 BeginPaint 将与 EndPaint 匹配。至于 GetDC,请注意 documentation 中的以下内容:

After painting with a common DC, the ReleaseDC function must be called to release the DC. Class and private DCs do not have to be released.