Clipboard
Reads and writes text from and to the Windows clipboard.
Archived content: This source code is currently inactive and may be outdated or no longer maintained or functional.
Mit diesen Funktionen kann man einfach Text aus der Windows-Zwischenablage auslesen oder darin speichern. Der Text wird dafür in einem einfach handhabbaren CString-Objekt gespeichert und man muss sich nicht mit den komplizierten Funktionsaufrufen und der Speicherverwaltung beschäftigen.
Eine CString-Implementierung ist ebenfalls verfügbar.
Note on the code quality: The content on this page is possibly a bit outdated. I’m not using C++ anymore for quite some time, but I would like to keep the existing and once useful functions available.
Download
Clipboard.cpp1.5 KiBQuelltext der Clipboard-Funktionen
Contents of the file Clipboard.cpp:
//
// Clear the clipboard with the EmptyClipboard() function.
//
// Dependencies: CString
//
// Web: http://unclassified.software/source/clipboard
// Gets the current clipboard text contents.
//
CString GetClipboardText()
{
HANDLE string;
char ret_text[4096];
// open clipboard for task
if (OpenClipboard(0))
{
// try reading if successful
if ((string = GetClipboardData(CF_TEXT)) != 0)
{
strncpy(ret_text, (char *) string, 4096);
ret_text[4095] = '\0';
CloseClipboard();
return ret_text;
}
else
{
CloseClipboard();
return "";
}
}
return "";
}
// Sets the clipboard contents to the specified text.
//
// Returns true on success, otherwise false.
//
bool CopyToClipboard(CString strText)
{
bool bRet = true;
if (strText.GetLength() > 0)
{
HGLOBAL hGlobalMemory;
LPVOID lpGlobalMemory;
// allocate global memory
hGlobalMemory = GlobalAlloc(GHND, strText.GetLength() + 1);
if (hGlobalMemory)
{
// lock block to get a pointer to it
lpGlobalMemory = GlobalLock(hGlobalMemory);
// copy string to the block
lpGlobalMemory = lstrcpy((char *) lpGlobalMemory,
strText.GetBuffer(strText.GetLength()));
// free memory
GlobalUnlock(hGlobalMemory);
// open clipboard for task
if (OpenClipboard(0))
{
EmptyClipboard();
// try writing if successful
if (!SetClipboardData(CF_TEXT, hGlobalMemory))
{
// error writing to clipboard
bRet = false;
}
CloseClipboard();
}
}
}
return bRet;
}
Licence and terms of use
This software is freely available as source code and compiled version, without restrictions (“public domain”). There is no warranty, not even for merchantability or fitness for a particular purpose. I am not liable for any damage caused through appropriate or inappropriate use.
Statistic data
- Created on 2007-04-02.