CreateCompatibleDC
The CreateCompatibleDC function creates a memory device context (DC) compatible with the specified device.
HDC CreateCompatibleDC( HDC hdc // handle to DC );
Parameters
-
hdc
- [in] Handle to an existing DC. If this handle is NULL, the function creates a memory DC compatible with the application's current screen.
Return Values
If the function succeeds, the return value is the handle to a memory DC.
If the function fails, the return value is NULL.
Windows NT/2000/XP: To get extended error information, call GetLastError.
Remarks
A memory DC exists only in memory. When the memory DC is created, its display surface is exactly one monochrome pixel wide and one monochrome pixel high. Before an application can use a memory DC for drawing operations, it must select a bitmap of the correct width and height into the DC. To select a bitmap into a DC, use the CreateCompatibleBitmap function, specifying the height, width, and color organization required.
When a memory DC is created, all attributes are set to normal default values. The memory DC can be used as a normal DC. You can set the attributes; obtain the current settings of its attributes; and select pens, brushes, and regions.
The CreateCompatibleDC function can only be used with devices that support raster operations. An application can determine whether a device supports these operations by calling the GetDeviceCaps function.
When you no longer need the memory DC, call the DeleteDC function.
Windows 2000 and later: If hdc is NULL, the thread that calls CreateCompatibleDC owns the HDC that is created. When this thread is destroyed, the HDC is no longer valid. Thus, if you create the HDC andpass it to another thread, then exit the first thread, the second thread will not be able to use the HDC.
ICM: If the DC that is passed to this function is enabled for Independent Color Management (ICM), the DC created by the function is ICM-enabled. The source and destination color spaces are specified in the DC.
Example Code
For an example, see Capturing an Image.
Requirements
Windows NT/2000/XP/Vista: Included in Windows NT 3.1 and later.
Windows 95/98/Me: Included in Windows 95 and later.
Header: Declared in Wingdi.h; include Windows.h.
Library: Use Gdi32.lib.
See Also
Device Contexts Overview, Device Context Functions, CreateCompatibleBitmap, DeleteDC, GetDeviceCaps
我按照如下方式创建兼容DC进行绘图,在某些机器上偶尔CreateCompatibleBitmap会失败,有点怀疑是内存不足什么的,可是机器内存一般都是512m以上了怎么还会出这种问题呢?后续处理中需要加什么释放DC或者释放CBitmap对象之类的操作吗? CDC m_MemDC; //成员变量,类对象被销毁时才被销毁 CBitmap m_Bitmap; CClientDC dc(this); m_MemDC.CreateCompatibleDC(&dc); //创建兼容DC m_Bitmap.CreateCompatibleBitmap(&dc, 1024,768); m_MemDC.SelectObject(&m_Bitmap);
为什么CreateCompatibleBitmap会失败呢?我有更好的答案
CDC/CBitmap都不需要释放操作了,析构函数里有释放操作(DeleteObject ) CBitmap* pBitmap m_MemDC.SelectObject(&m_Bitmap); ........ m_MemDC.SelectObject(pBitmap); //这里是必要的。