How to copy string to clipboard in C?

前端 未结 3 1613
星月不相逢
星月不相逢 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 01:57

    I wrote an open source command line tool to do this in Windows:

    http://coffeeghost.net/2008/07/25/ccwdexe-copy-current-working-directory-command/

    ccwd.exe copies the current working directory to the clipboard. It's handy when I'm several levels deep into a source repo and need to copy the path.

    Here's the complete source:

    #include "stdafx.h"
    #include "windows.h"
    #include "string.h"
    #include <direct.h>
    
    int main()
    {
        LPWSTR cwdBuffer;
    
        // Get the current working directory:
        if( (cwdBuffer = _wgetcwd( NULL, 0 )) == NULL )
            return 1;
    
        DWORD len = wcslen(cwdBuffer);
        HGLOBAL hdst;
        LPWSTR dst;
    
        // Allocate string for cwd
        hdst = GlobalAlloc(GMEM_MOVEABLE | GMEM_DDESHARE, (len + 1) * sizeof(WCHAR));
        dst = (LPWSTR)GlobalLock(hdst);
        memcpy(dst, cwdBuffer, len * sizeof(WCHAR));
        dst[len] = 0;
        GlobalUnlock(hdst);
    
        // Set clipboard data
        if (!OpenClipboard(NULL)) return GetLastError();
        EmptyClipboard();
        if (!SetClipboardData(CF_UNICODETEXT, hdst)) return GetLastError();
        CloseClipboard();
    
        free(cwdBuffer);
        return 0;
    }
    
    0 讨论(0)
  • 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();
    
    0 讨论(0)
  • 2020-11-30 02:02

    Take a look at Microsoft's Documentation on using the clipboard. This requires that your using the WinAPI, but this shouldn't be a problem since your on Windows. Note that programming the Windows API is never simple unless you use a very high-level language.

    0 讨论(0)
提交回复
热议问题