c++ - 不调用 ReleaseDC 可能会发生什么坏事?

标签 c++ winapi opengl graphics gdi

用C++编程,一旦我们通过GetDC获得context device就可以使用了。如果我们不调用ReleaseDC就退出程序会发生什么不好的事情?

最佳答案

来自 the docs

The ReleaseDC function releases a device context (DC), freeing it for use by other applications. The effect of the ReleaseDC function depends on the type of DC. It frees only common and window DCs. It has no effect on class or private DCs.

如您所见,如果其他应用程序可以访问同一 DC,则可能需要它。

无论如何,最好使用 C++ RAII idiom对于这种事情。考虑这个类:

class ScopedDC
{
   public:
      ScopedDC(HDC handle):handle(handle){}
      ~ScopedDC() { ReleaseDC(handle); }
      HDC get() const {return handle; }
   //disable copying. Same can be achieved by deriving from boost::noncopyable
   private:
      ScopedDC(const ScopedDC&);
      ScopedDC& operator = (const ScopedDC&); 

   private:
      HDC handle;
};

使用这个类你可以这样做:

{
   ScopedDC dc(GetDC());
   //do stuff with dc.get();
}  //DC is automatically released here, even in case of exceptions

关于c++ - 不调用 ReleaseDC 可能会发生什么坏事?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7219640/

相关文章:

c++ - 如何使用 SetWinEventHook() 函数获取事件窗口更改消息

c++ - 在 C++ 中从屏幕选择创建位图时的黑色图像

c - 带 OpenGL 的嵌套剪刀盒

c++ - 让 GLEW 在 Code::Blocks 中进行编译

c++ - 从 C++ 调用 python eval

c++ - 如何阻止命令接受输入?

c++ - 错误 : declaration of 'operator<<' as non-function|

c++ - 错误 : implicit declaration of function `int open(...)'

c++ - 在没有 DirectX 的情况下在 Windows 上获得精确的屏幕刷新率?

c - 位图字体渲染问题