How to copy string to clipboard in C?

前端 未结 3 1634
星月不相逢
星月不相逢 2020-11-30 01:35

The SetClipboardData function requires a HANDLE reference; I\'m having trouble converting my string for use in the function.

Here is my cod

3条回答
  •  没有蜡笔的小新
    2020-11-30 02:02

    Read the MSDN documentation for the SetClipboardData function. It appears you are missing a few steps and releasing the memory prematurely. First of all, you must call OpenClipboard before you can use SetClipboardData. Secondly, the system takes ownership of the memory passed to the clipboard and it must be unlocked. Also, the memory must be movable, which requires the GMEM_MOVEABLE flag as used with GlobalAlloc (instead of LocalAlloc).

    const char* output = "Test";
    const size_t len = strlen(output) + 1;
    HGLOBAL hMem =  GlobalAlloc(GMEM_MOVEABLE, len);
    memcpy(GlobalLock(hMem), output, len);
    GlobalUnlock(hMem);
    OpenClipboard(0);
    EmptyClipboard();
    SetClipboardData(CF_TEXT, hMem);
    CloseClipboard();
    

提交回复
热议问题