SteinSOFT.net
  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))
   {
      return;
   }
  
   //clear clipboard
   EmptyClipboard();
 
   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));
   GlobalUnlock(clipbuffer);
   
   //fill the clipboard with data
   //CF_TEXT indicates that the buffer is a text-string
   ::SetClipboardData(CF_TEXT,clipbuffer);
   //close clipboard as we don't need it anymore
   CloseClipboard();
}

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!

Copyright © by SteinSOFT