拷贝位图到剪接板非常简单,唯一要注意的是,如果位图需要调色板才能正确显示,则也要拷贝调色板。
函数一:拷贝设备相关位图到调色板
// CopyBitmapToClipboard - Copies a device-dependent bitmap to clipboard // pWnd - Pointer to window that opens the clipboard // bitmap - The device-dependent bitmap // pPal - Pointer to logical palette - Can be NULL // NOTE - GDI objects are detached from bitmap & pPal // as the clipboard owns them after the copy void CopyBitmapToClipboard( const CWnd *pWnd, CBitmap& bitmap, CPalette* pPal ) { ::OpenClipboard(pWnd->GetSafeHwnd()); ::EmptyClipboard() ; if( pPal ) ::SetClipboardData (CF_PALETTE, pPal->GetSafeHandle() ) ; ::SetClipboardData (CF_BITMAP, bitmap.GetSafeHandle() ) ; ::CloseClipboard () ; bitmap.Detach(); if( pPal ) pPal->Detach(); }函数二:拷贝设备无关位图到剪接板
CopyDIBToClipboard()与CopyBitmapToClipboard()非常相似,内存句柄包含BITMAPINFO,位图首先要使用GlobalAlloc()分配内存。一旦DIB拷贝到剪接板,内存句柄就被剪接板拥有,并不能让应用程序释放。
// CopyDIBToClipboard - Copies a device-dependent bitmap to clipboard // pWnd - Pointer to window that opens the clipboard // hDIB - Memory handle that contains BITMAPINFO & bitmap bits // pPal - Pointer to logical palette - Can be NULL // NOTE - GDI objects are detached from bitmap & pPal // as the clipboard owns them after the copy void CopyDIBToClipboard( const CWnd *pWnd, HGLOBAL hDIB, CPalette* pPal ) { ::OpenClipboard(pWnd->GetSafeHwnd()); ::EmptyClipboard(); if( pPal ) ::SetClipboardData (CF_PALETTE, pPal->GetSafeHandle() ) ; ::SetClipboardData (CF_DIB, hDIB ) ; ::CloseClipboard () ; bitmap.Detach(); if( pPal ) pPal->Detach(); }函数三:拷贝窗口图像到剪接板
CopyWndToClipboard()函数拷贝窗口图像到剪接板。
void CopyWndToClipboard( CWnd *pWnd ) { CBitmap bitmap; CClientDC dc(pWnd); CDC memDC; CRect rect; memDC.CreateCompatibleDC(&dc); pWnd->GetWindowRect(rect); bitmap.CreateCompatibleBitmap(&dc, rect.Width(),rect.Height() ); CBitmap* pOldBitmap = memDC.SelectObject(&bitmap); memDC.BitBlt(0, 0, rect.Width(),rect.Height(), &dc, 0, 0, SRCCOPY); pWnd->OpenClipboard() ; EmptyClipboard() ; SetClipboardData (CF_BITMAP, bitmap.GetSafeHandle() ) ; CloseClipboard () ; memDC.SelectObject(pOldBitmap); bitmap.Detach(); }