Copying Text to the Clipboard

Apr 12, 2008
This article was written back when Visual Studio 6 was new. As such, I cannot guarantee that the content of this article still applies in modern Windows environments.

Sending the contents of a CString object to the clipboard is a quick and easy task when the following function is used:

BOOL SendTextToClipboard(CString source)
{
    // Return value is TRUE if the text was sent
    // Return value is FALSE if something went wrong
    if(OpenClipboard())
    {
        HGLOBAL clipbuffer;
        char* buffer;

        EmptyClipboard(); // Empty whatever's already there

        clipbuffer = GlobalAlloc(GMEM_DDESHARE, source.GetLength()+1);
        buffer = (char*)GlobalLock(clipbuffer);
        strcpy(buffer, LPCSTR(source));
        GlobalUnlock(clipbuffer);

        SetClipboardData(CF_TEXT, clipbuffer); // Send the data

        CloseClipboard(); // VERY IMPORTANT
        return TRUE;
    }
    return FALSE;
}

So what's going on here? We first test to see if we can successfully open the clipboard from our program. Note that once we have called the OpenClipboard() function, no other program can modify the clipboard contents. Because of this, it is very important that later on in our code we call the CloseClipboard() function. This way, others can access the clipboard as needed.

We create a local handle to a global memory block as well as a local character buffer. A call to the EmptyClipboard() function clears out anything that might already be on the clipboard. Following that, we allocate a specified number of bytes in the global memory heap. This is where the string will be stored for future use. We then lock the global memory block (so we don't lose our storage), assigning the memory pointer as necessary. Then we copy the text from the CString into the character buffer, unlock the global memory storage chunk and send the data to the clipboard.

Finally, we call the CloseClipboard() function! The code then ends by returning true (since we successfully copied the text).

No comments (yet!)

Leave a Comment

Ignore this field:
Never displayed
Leave this blank:
Optional; will not be indexed
Ignore this field:
Both Markdown and a limited set of HTML tags are supported
Leave this empty: