Click here to Skip to main content
Licence CPOL
First Posted 25 Nov 1999
Views 185,840
Bookmarked 108 times

Clipboard Copy in a Nutshell

By | 25 Nov 1999 | Article
Clipboard copy in a nutshell.

Supporting copy is usually straightforward for most applications. It usually requires 10-20 lines of code. But like many features of MFC, the implementation is simple. However, finding the information needed to create the implementation is tedious and time consuming. To save you many hours of reading documentation, I have included several common methods for placing data on the clipboard.

Copying a Bitmap of the Client Area

The following bit of code renders the client area using OnDraw() into a bitmap. The bitmap is placed on the clipboard as a CF_BITMAP that is recognizable by most applications that accept bitmaps. This code will work will all mapping modes provided that mapping mode is set in the OnPrepareDC() function.

void CXStitchView::OnEditCopy() 
{
    CRect       rect;
    CClientDC   dc(this);
    CDC         memDC;
    CBitmap     bitmap;
    
    GetClientRect(&rect); 

    // Create memDC
    memDC.CreateCompatibleDC(&dc);
    bitmap.CreateCompatibleBitmap(&dc, rect.Width(), rect.Height());
    CBitmap* pOldBitmap = memDC.SelectObject(&bitmap);

    // Fill in memDC
    memDC.FillSolidRect(rect, dc.GetBkColor()); 
    OnPrepareDC(&memDC);
    OnDraw(&memDC);

    // Copy contents of memDC to clipboard
    OpenClipboard();
    EmptyClipboard();
    SetClipboardData(CF_BITMAP, bitmap.GetSafeHandle());
    CloseClipboard();

    // Clean up
    memDC.SelectObject(pOldBitmap);
    bitmap.Detach();
}

Copying a Table of Data to the Clipboard

Placing a table of data on the clipboard is easy. It is simply a string of text. Tabs separate columns, new lines separate rows. Here's some example source.

#include <afxpriv.h>

void CClipExamView::OnEditCopy() 
{
    // Create a shared memory file
    CSharedFile sf(GMEM_MOVEABLE | GMEM_SHARE | GMEM_ZEROINIT);

    // Place clipboard data in the shared memory file
    RenderTableData(sf);

    if (sf.GetLength() > 0) {
        // Put the data on the clipboard
        OpenClipboard();
        EmptyClipboard();
        SetClipboardData(CF_TEXT, sf.Detach());
        CloseClipboard();
    }
}

void CClipExamView::RenderTableData(CFile &file)
{
    // Columns are separated by tabs ('\t')
    // Rows are separated by new lines ('\n')
    CString buffer = "1\t2\t3\n4\t5\t6\n";
    file.Write(buffer, buffer.GetLength()); 
}

Copying Formatted Data to the Clipboard

Formatted text can support bold, italic or any other formatting that can be done in a word processor. Formatted text is usually placed on the clipboard as RTF (Rich Text Format).

The Rich Text Format is intended as an interchange format for Word-processing applications. Because of that, it is a rather large and feature rich file format. Fortunately, it is possible to describe a minimal RTF command set for creating simple formatted documents.

Basic RTF commands:

\par - Starts a new paragraph. 
\tab - A tab. 
\b - Enable Bold (scoped within a group) 
\i - Enable Italics (scoped within a group) 
\ul - Enable Underline (scoped within a group)

For example, the RTF string:

{\rtf1 {1 \tab 2 \tab 3 \par 4 \tab {\b\i 5} \tab 6}}

Source

#include <afxpriv.h>

void CClipExamView::OnEditCopy() 
{
    // Create a shared memory file
    CSharedFile sf(GMEM_MOVEABLE | GMEM_SHARE | GMEM_ZEROINIT);

    // Place clipboard data in the shared memory file
    RenderFormattedData(sf);

    if (sf.GetLength() > 0) {
        // Put the data on the clipboard
        OpenClipboard();
        EmptyClipboard();
        SetClipboardData(::RegisterClipboardFormat(CF_RTF), sf.Detach());
        CloseClipboard();
    }
}

void CClipExamView::RenderFormattedData(CFile &file)
{
    // RTF (Rich Text Format) - Don't forget to escape
    // the \ character in your C strings!
    CString buffer = "{\\rtf1 {1 \\tab 2 \\tab 3" 
               " \\par 4 \\tab {\\b\\i 5} \\tab 6}}";
    file.Write(buffer, buffer.GetLength()); 
}

Getting More Info on RTF

Most books on file format address RTF in some form. You can find the RTF specification here.

Virtually all word processors can save RTF files. This is usually a good place to start when building an RTF template.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Keith Rule

Web Developer

United States United States

Member

I work at Tektronix in Beaverton OR. I've been programming for fun since 1975 (I started while in a Computer Explorer Scout group in Spokane WA). I've been programming in C since 1979 and I've been working professionally since 1983.
 
I really enjoy www.codeproject.com. It has saved me an incredible amount of time. I only hope my small contributions have given back some of what I've taken.

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board. (secure sign-in)
 
Search this forum  
 FAQ
    Noise  Layout  Per page   
  Refresh
GeneralClipboard Data Store Pinmembereg_Anubhava21:55 5 May '10  
Questioncopy tabular data (text and images) to clipboard? PinmemberNachtalb23:13 15 May '08  
Questionplease can you help me to copy file? Pinmemberyummy_yummy0:45 19 Aug '06  
GeneralClipboard Query. PinmemberHakuna-Matada1:44 3 Aug '06  
GeneralA little additon PinmemberAlexSr1:13 7 Dec '04  
GeneralThanx, Good Work PinmemberBugSearcher0:09 13 Sep '04  
Generalquestion PinsussAnonymous19:19 21 Dec '02  
Generalcatching the CTRL+V PinsussM.A.10:12 18 Dec '02  
Generalconvert clipboard data to bytes PinsussAnonymous7:19 31 Jul '02  
GeneralWord file PinmemberLai The Thoi21:42 27 Jan '02  
QuestionHow can I disable copy to clipboard PinmemberAnonymous0:17 22 Aug '01  
AnswerRe: How can I disable copy to clipboard PinsussAnonymous0:56 22 Apr '04  
GeneralMultiple PinmemberKonstantin S. Diguine4:02 6 Apr '01  
GeneralCXStitchView PinmemberAlexMarbus10:11 2 Mar '01  
GeneralRe: CXStitchView PinmemberKeith12:42 5 Mar '01  
You're right. I was teaching an MFC class when I wrote up this example for CodeProject. The group project was to create a cross stitch editor. The theory being that this was a program that was feasible for a 400 level group project that had the following properies:
 
1) None of the students probably knew anything about cross stitching.
2) I could readily explain to them what cross stitching was in a few minutes.
3) All of the student's probably knew someone who did cross stitch.
4) The knowledge of MFC required for this project could be taught in just a few weeks.
 
The result was, shall we say, interesting. I think it was a learning experence for everyone (including my self). For the most part a cross stitch editor was the right level of project an met my goals. I'm not sure that the students found it terribly interesting though. They seemed to like the screen saver individual project best.
 
Keith
GeneralRe: CXStitchView PinmemberAlexMarbus12:45 5 Mar '01  
QuestionHow can I... PinmemberBernd Giesen0:10 1 Dec '00  
AnswerRe: How can I... PinmemberCraig Henderson5:41 14 Dec '00  

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Mobile
Web03 | 2.5.120529.1 | Last Updated 26 Nov 1999
Article Copyright 1999 by Keith Rule
Everything else Copyright © CodeProject, 1999-2012
Terms of Use
Layout: fixed | fluid