8
votes

The add-to-clip-board code we have in our code base is quite low-level - allocating global memory and so on. For the simple case I just want to put some plain text on the clipboard, are there any routines which can wrap all that stuff?

An example is that CRichEditCtrl has Copy() & Cut() methods which automatically put the current selection on the clipboard. Does MFC make this kind of functionality available in isolation?

Update: Created a new question based on mwigdahl's response

1
Only one I know of is msdn.microsoft.com/en-us/library/sze892zx%28VS.80%29.aspx which I assume is what you are already using. Even if not it hardly gives you much extra as you almost certainly still need to to call GlobalAlloc or similar.tyranid

1 Answers

6
votes

No, but it's not that hard to wrap it yourself. Adapted from Frost Code (and untested):

void SetClipboardText(CString & szData)
{
    HGLOBAL h;
    LPTSTR arr;

    h=GlobalAlloc(GMEM_MOVEABLE, szData.GetLength()+1);
    arr=(LPTSTR)GlobalLock(h);
    strcpy_s((char*)arr, szData.GetLength()+1, szData.GetBuffer());
    szData.ReleaseBuffer();
    GlobalUnlock(h);

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