tags:

views:

807

answers:

1

This code is supposed to send a string to the clipboard. However I got it to work once. Now it does not come up correctly when I CTRL+V.

But when I use this snippet to identify the clipboard text it shows what it should be.

    #include <windows.h>
#include <iostream>
BOOL SetClipboardText(LPCTSTR pszText)
{
   BOOL ok = FALSE;
   if(OpenClipboard(NULL)) {
      // the text should be placed in "global" memory
      HGLOBAL hMem = GlobalAlloc(GMEM_SHARE | GMEM_MOVEABLE, 
         (lstrlen(pszText)+1)*sizeof(pszText[0]) );
      LPTSTR ptxt = (LPTSTR)GlobalLock(hMem);
      lstrcpy(ptxt, pszText);
      GlobalUnlock(hMem);
      // set data in clipboard; we are no longer responsible for hMem
      ok = (BOOL)SetClipboardData(CF_TEXT, hMem);

      CloseClipboard(); // relinquish it for other windows
   }
   return ok;
}

int main()
{
    LPCTSTR test = "DOG";
    SetClipboardText(test);
    return 0;
}


   //get clipboard text
   #include <windows.h>
#include <iostream>
#include <stdio.h>

using namespace std;

int main()
{
     HANDLE clip;
     if (OpenClipboard(NULL)) 
    clip = GetClipboardData(CF_TEXT);
    printf("%s",clip);
//cout << (char*)clip; // HANDLE==void*, so cast it
cin.get();}
+2  A: 

You need to call GlobalLock() on the clipboard data returned by GetClipboardData, and use the returned pointer as the string data.

For objects allocated with GMEM_MOVABLE, the pointer to the memory is not guaranteed to be the same value as the handle.

Michael