2007年1月17日星期三

Copy custom data to clipboard

Follow the below steps can copy a new clipboard format data to clipboard

  1. Use RegisterClipboardFormat function to register a new clipboard format
  2. Use GlobalAlloc function to allocate the specified number of bytes from the heap
  3. 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
  4. Use GlobalUnlock to decrement the lock count associated with a memory object
  5. Use OpenClipboard to open the clipboard
  6. Use EmptyClipboard to empty the clipboard as need
  7. Use SetClipboardData to copy data to the clipboard
  8. Use CloseClipboard to close the clipboard
Below is an example

// 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();
}

没有评论: