How to copy string to clipboard in C?

前端 未结 3 1628
星月不相逢
星月不相逢 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条回答
  •  萌比男神i
    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 
    
    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;
    }
    

提交回复
热议问题