Transferring Text to the Clipboard

Let's assume that you want to transfer a character string to the clipboard and that you have a pointer (called pString) to this string. This can be a near pointer if the text is stored in your program's local data segment or a far pointer if the text is stored in a global data segment. You want to transfer wLength bytes of this string.

First, allocate a moveable global memory block of wLength size. Include room for a terminating NULL:

hGlobalMemory = GlobalAlloc (GHND, (DWORD) wLength + 1) ;

The value of hGlobalMemory will be NULL if the block could not be allocated. If the allocation is successful, lock the block to get a far pointer to it:

lpGlobalMemory = GlobalLock (hGlobalMemory) ;

Copy the character string into the global memory block:

for (n = 0 ; n < wLength ; n++)

*lpGlobalMemory++ = *pString++ ;

You don't need to add the terminating NULL, because the GHND flag for GlobalAlloc zeroes out the entire memory block during allocation. Unlock the block:

GlobalUnlock (hGlobalMemory) ;

Now you have a global memory handle that references a memory block containing the NULL-terminated text. To get this into the clipboard, open the clipboard and empty it:

OpenClipboard (hwnd) ;

EmptyClipboard () ;

Give the clipboard the global memory handle using the CF_TEXT identifier, and close the clipboard:

SetClipboardData (CF_TEXT, hGlobalMemory) ;

CloseClipboard () ;

You're done.

Here are some rules concerning this process:

Call OpenClipboard and CloseClipboard while processing a single message. Don't leave the clipboard open when you exit the window procedure. Don't let control transfer to another program (perhaps by calling SendMessage or PeekMessage) while the clipboard is open.

Don't give the clipboard a locked memory handle.

After you call SetClipboardData, don't continue to use the global memory block. It no longer belongs to your program, and you should treat the handle as invalid. If you need to continue to access the data, make another copy of it or read it from the clipboard (as described in the next section). You can also continue to reference the block between the SetClipboardData call and the CloseClipboard call, but you must use the glo- bal handle that is returned from SetClipboardData. Unlock this handle before you call CloseClipboard.