Copying a Bitmap to the Clipboard with MFC

ID: Q112530


The information in this article applies to:


SUMMARY

In order to pass a handle to a Bitmap to the clipboard, you have to get it from the GetSafeHandle method and then "detach" it from the objects that are using it so the clipboard has the only handle.


MORE INFORMATION

Here is a sample application that can be used to copy a bitmap from the client window to the clipboard. The easiest way to implement this is to follow these steps:

  1. Begin by building your application with AppWizard.


  2. Select the Browse ClassWizard menu.


  3. Select the Message Maps tab. In the Object IDs listbox, select ID_EDIT_COPY. In the Messages listbox, select Command. The Add function button will hilight. Press it to create the function.


  4. Press the Edit Code button. It will then take you to the CClipmfcView::OnEditCopy() function.


  5. From here, you need to add the following code:


Sample Code


void CClipmfcView::OnEditCopy()
{
    // TODO: Add your command handler code here
    CBitmap     cBmp;
    CClientDC   cWndDC(this);   // View is an hWnd, so we can use "this"
    CDC         cMemDC;         // Handle to a memory DC
    CRect     rect;             // For storing the size of the window

    cMemDC.CreateCompatibleDC(&cWndDC); // Create the memory DC.

    GetWindowRect(rect);         // Get the size of the window
    // Here we are going to do a little drawing so we can see a line.
    cWndDC.MoveTo(0,0);
    cWndDC.LineTo(rect.Width(),rect.Height());

    cBmp.CreateCompatibleBitmap(&cWndDC, rect.Width(),rect.Height() );
    // Keep the old bitmap
    CBitmap* pOldBitmap = cMemDC.SelectObject(&cBmp);

    cMemDC.BitBlt(0, 0, rect.Width(),rect.Height(), &cWndDC, 0, 0,
SRCCOPY);


    // here are the actual clipboard functions.
    AfxGetApp()->m_pMainWnd->OpenClipboard() ;
    EmptyClipboard() ;
    SetClipboardData (CF_BITMAP, cBmp.GetSafeHandle() ) ;
    CloseClipboard () ;
        // next we select the old bitmap back into the memory DC
        // so that our bitmap is not deleted when cMemDC is destroyed.
        // Then we detach the bitmap handle from the cBmp object so that
        // the bitmap is not deleted when cBmp is destroyed.
    cMemDC.SelectObject(pOldBitmap);
    cBmp.Detach();

    return;
} 

Additional query words: kbdsupport


Keywords          : kb16bitonly kbnokeyword kbMFC kbVC 
Version           : 7.00   | 1.00 1.50
Platform          : MS-DOS WINDOWS 
Issue type        : 

Last Reviewed: August 2, 1999