The help you needed in C, C++, MFC
Complete tutorials with free source code
PDF Print E-mail

How to write a string to Windows clipboard

In this article, we will see how we can write a text string to Windows clipboard. The task is not that difficult.

Straight away, here is the code.

HGLOBAL h;
LPTSTR arr;
char *temp = "I am in the clipboard!";

h=GlobalAlloc(GMEM_MOVEABLE, 23);
arr=(LPTSTR)GlobalLock(h);
strcpy_s((char*)arr, 23, temp);
GlobalUnlock(h);

::OpenClipboard (NULL);
EmptyClipboard();
SetClipboardData(CF_TEXT, h);
CloseClipboard();

First, we have to allocate memory in heap to store the string we are going to put in the clipboard. We allocate memory using Win32  API function GlobalAlloc(). Then, we call GlobalLock() to lock the memory we allocated in heap and obtain a pointer to the starting memory address of our allocated memory. Then, using strcpy_s, we copy our string to the memory we allocated in heap.

Then, first we have to open the clipboard and empty the data on it using Win32 functions OpenClipboard and EmptyClipboard. Then, we call SetClipboardData to put the data on the memory we allocated in heap to the clipboard. We have to use CF_TEXT as the format of clipboard data because we are going to put a text string to the clipboard. There are many other data formats we can put in the clipboard such as a bitmap (CF_BITMAP).

The sample application just put the string to clipboard when a button is pressed.

Download source code of sample application