Code Snippets
What's That?
I am using it actively
I planning to use/learn it
I don't plan to lean/use it
5th option
Home :: Programming :: Code Snippets :: MfcWin :: Copying Text to the Clipboard

[ Copying Text to the Clipboard ]

Coyping text to the clipboard and later pasting it in another window is one of the most useful things of an graphical environment like Windows. And the user indirectly expects that every application supports this nice feature. Fortunately you can do this in only a few lines of code.

Here is the function that will do everything for you. It takes the current window handle and a pointer to the string that should be copied as parameters. Here's the example code:

void CopyToClipboard(const char* stringbuffer, HWND window)
   //try to open clipboard first
   if (!OpenClipboard(window))
   //clear clipboard
   HGLOBAL clipbuffer;
   char * buffer;
   //alloc enough mem for the string;
   //must be GMEM_DDESHARE to work with the clipboard
   clipbuffer = GlobalAlloc(GMEM_DDESHARE, strlen(stringbuffer)+1);
   buffer = (char*)GlobalLock(clipbuffer);
   strcpy(buffer, LPCSTR(stringbuffer));
   //fill the clipboard with data
   //CF_TEXT indicates that the buffer is a text-string
   //close clipboard as we don't need it anymore

Easy, eh? Simply copy this code in your project and it will be ready to use. Only thing to do is to include string.h as the function strlen(..) is used.

The code is pretty self-explanatory. First you open the clipboard and empty it then you allocate memory for the string using GlobalAlloc(..). This is indeed the only problem of the code. You have to use this function and with GMEM_DDESHARE as first parameter - no text would be copied otherwise. The clipboard will be updated with a call of SetClipboardData(..) and CF_TEXT as parameter meaning a standard text string.

That's it! If you are still in doubt ask your questions in the message board or simply drop me some lines. Happy Coding!

 Last edited 2002-12-08 01:05:18 by André Stein - printable version
» copyright by andré stein
» using stCM v1.0
» steinsoft.net revision 5.0