How to Copy/Paste from the Clipboard in C++

How to copy string to clipboard in C?

Read the MSDN documentation for the SetClipboardData function. It appears you are missing a few steps and releasing the memory prematurely. First of all, you must call
OpenClipboard before you can use SetClipboardData. Secondly, the system takes ownership of the memory passed to the clipboard and it must be unlocked. Also, the memory must be movable, which requires the GMEM_MOVEABLE flag as used with GlobalAlloc (instead of LocalAlloc).

const char* output = "Test";
const size_t len = strlen(output) + 1;
HGLOBAL hMem = GlobalAlloc(GMEM_MOVEABLE, len);
memcpy(GlobalLock(hMem), output, len);
GlobalUnlock(hMem);
OpenClipboard(0);
EmptyClipboard();
SetClipboardData(CF_TEXT, hMem);
CloseClipboard();

how to copy text to the clipborad in c++?

SetClipboardData should handle it.

glob = GlobalAlloc(GMEM_FIXED,32);
memcpy(glob,"it works",9);

OpenClipboard(hWnd);
EmptyClipboard();
SetClipboardData(CF_TEXT,glob);
CloseClipboard();

EDIT

This will get data out of clipboard and return that data in string.

std::string GetClipboardText()
{
OpenClipboard(nullptr);
HANDLE hData = GetClipboardData(CF_TEXT);

char * pszText = static_cast<char*>( GlobalLock(hData) );
std::string text( pszText );

GlobalUnlock( hData );
CloseClipboard();

return text;
}

How do you copy/paste from the clipboard in C++?

In windows look at the following API:

  • OpenClipBoard
  • EmptyClipboard
  • SetClipboardData
  • CloseClipboard
  • GetClipboardData

An extensive discussion can be found here.
Obviously this topic is strongly operating system related. And if you are using some framework (ie MFC/ATL) you generally find some helper infrastructure. This reply refer to the lowest API level in WIndows. If you are planning to use MFC have a look here, if you prefer ATL look here.

How do I copy the contents of a String to the clipboard in C#?

You can use System.Windows.Forms.Clipboard.SetText(...).

is there a way to take an item you have copied to clipboard and save it as a var or int

#include <windows.h>
//get data
HANDLE clip;
string clip_text = "";

if (OpenClipboard(NULL))
{
clip = GetClipboardData(CF_TEXT);
clip_text = (char*)clip;
cout << "Text: "<<clip_text<<endl<<endl;
CloseClipboard();
}

works with WINDOWS ONLY!

Check these links:
http://www.cplusplus.com/forum/beginner/27836/

https://learn.microsoft.com/en-us/cpp/mfc/clipboard-using-the-windows-clipboard?view=msvc-160



Related Topics



Leave a reply



Submit