Clipboard Functions (User32)
The Clipboard API provides functions to transfer data between applications. Use these functions to open, modify, and retrieve clipboard contents.
Overview
Functions
Examples
The clipboard holds data in one or more formats. Applications must open the clipboard before reading or modifying its contents.
- OpenClipboard – Acquire ownership.
- CloseClipboard – Release ownership.
- EmptyClipboard – Remove all data.
- SetClipboardData – Place data on the clipboard.
- GetClipboardData – Retrieve data from the clipboard.
OpenClipboard
BOOL OpenClipboard(HWND hWndNewOwner);
Opens the clipboard for examination and prevents other applications from modifying the clipboard content.
CloseClipboard
BOOL CloseClipboard(void);
Closes the clipboard.
EmptyClipboard
BOOL EmptyClipboard(void);
Empties the clipboard and frees handles to data in the clipboard.
SetClipboardData
HANDLE SetClipboardData(UINT uFormat, HANDLE hMem);
Places data on the clipboard in a specified format.
GetClipboardData
HANDLE GetClipboardData(UINT uFormat);
Retrieves data from the clipboard in a specified format.
IsClipboardFormatAvailable
BOOL IsClipboardFormatAvailable(UINT format);
Determines whether the clipboard contains data in a specified format.
Copy Text to Clipboard (C++)
#include <windows.h>
#include <string>
bool CopyText(const std::wstring& text)
{
if (!OpenClipboard(nullptr)) return false;
EmptyClipboard();
size_t size = (text.size() + 1) * sizeof(wchar_t);
HGLOBAL hGlob = GlobalAlloc(GMEM_MOVEABLE, size);
if (!hGlob) { CloseClipboard(); return false; }
void* pData = GlobalLock(hGlob);
memcpy(pData, text.c_str(), size);
GlobalUnlock(hGlob);
SetClipboardData(CF_UNICODETEXT, hGlob);
CloseClipboard();
return true;
}
Paste Text from Clipboard (C++)
#include <windows.h>
#include <string>
std::wstring PasteText()
{
std::wstring result;
if (!OpenClipboard(nullptr)) return result;
if (IsClipboardFormatAvailable(CF_UNICODETEXT))
{
HANDLE hData = GetClipboardData(CF_UNICODETEXT);
if (hData)
{
const wchar_t* pText = static_cast(GlobalLock(hData));
if (pText) result = pText;
GlobalUnlock(hData);
}
}
CloseClipboard();
return result;
}