C / C ++ Windows API sending text to clipboard

This code should send a string to the clipboard. However, I made it work once. Now this does not work 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();}
+3
source share
1 answer

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

For objects allocated using GMEM_MOVABLE, a pointer to memory is not guaranteed to the same value as the descriptor.

+3
source

Source: https://habr.com/ru/post/1707727/


All Articles