Getting text from the clipboard is only a little more complex than transferring text to the clipboard. You must first determine whether the clipboard does in fact contain data in the CF_TEXT format. One of the easiest methods is to use the call:
bAvailable = IsClipboardFormatAvailable (CF_TEXT) ;
This function returns TRUE (nonzero) if the clipboard contains CF_TEXT data. We used this function in the POPPAD2 program in Chapter 9 to determine whether the Paste item on the Edit menu should be enabled or grayed. IsClipboardFormatAvailable is one of the few clipboard functions that you can use without first opening the clipboard. However, if you later open the clipboard to get this text, you should also check again (using the same function or one of the other methods) to determine if the CF_TEXT data is still in the clipboard.
To transfer the text out, first open the clipboard:
OpenClipboard (hwnd) ;
Obtain the handle to the global memory block referencing the text:
hClipMemory = GetClipboardData (CF_TEXT) ;
This handle will be NULL if the clipboard doesn't contain data in the CF_TEXT format. This is another way to determine if the clipboard contains text. If GetClipboardData returns NULL, close the clipboard without doing anything else.
The handle you receive from GetClipboardData doesn't belong to your program—it belongs to the clipboard. The handle is valid only between the GetClipboardData and CloseClipboard calls. You can't free that handle or alter the data it references. If you need to have continued access to the data, you should make a copy of the memory block.
Here's one method for copying the data into a global memory segment that belongs to your program. First, allocate a global memory block of the same size as that referenced by hClipMemory:
hMyMemory = GlobalAlloc (GHND, GlobalSize (hClipMemory)) ;
Check for a NULL value from GlobalAlloc to determine if the block was really allocated. If it was allocated, lock both handles and get pointers to the beginning of the blocks:
lpClipMemory = GlobalLock (hClipMemory) ;
lpMyMemory = GlobalLock (hMyMemory) ;
Because the character string is NULL-terminated, you can transfer the data using Windows' lstrcpy function:
lstrcpy (lpMyMemory, lpClipMemory) ;
Or you can use some simple C code:
while (*lpMyMemory++ = *lpClipMemory++) ;
Unlock both blocks:
GlobalUnlock (hClipMemory) ;
GlobalUnlock (hMyMemory) ;
Finally, close the clipboard:
CloseClipboard () ;
Now you have a global handle called hMyMemory that you can later lock to access this data.