Copy custom data to clipboard
Follow the below steps can copy a new clipboard format data to clipboard
- Use RegisterClipboardFormat function to register a new clipboard format
- Use GlobalAlloc function to allocate the specified number of bytes from the heap
- Use GlobalLock function to get a pointer to the first byte of the object's memory block, and then use memcpy to copy data to this pointer
- Use GlobalUnlock to decrement the lock count associated with a memory object
- Use OpenClipboard to open the clipboard
- Use EmptyClipboard to empty the clipboard as need
- Use SetClipboardData to copy data to the clipboard
- Use CloseClipboard to close the clipboard
// Custom data
unsigned char cData[] = {0x01, 0x02, 0x32, 0x45};
int dLen = sizeof(cData)/sizeof(unsigned char);
// Register a new clipboard format named "cf/new-cf-name"
UINT cfType = RegisterClipboardFormat("cf/new-cf-name");
if (!cfType) {
AfxMessageBox("Register clipboard format error");
return;
}
// Alloc
HGLOBAL hGlobalData = GlobalAlloc(GMEM_DDESHARE, dLen);
if (!hGlobalData)
{
return;
}
// Lock the handle and copy the custom data to the buffer.
char* sData = (char*)GlobalLock(hGlobalData);
memcpy(sData, cData, dLen);
GlobalUnlock(hGlobalData);
// Open Clipboard
if (OpenClipboard())
{
// Remove the current Clipboard contents
if (EmptyClipboard())
{
if (!::SetClipboardData(cfType, hGlobalData)) {
AfxMessageBox("Unable to set Clipboard data");
}
}
CloseClipboard();
}
没有评论:
发表评论