Search code examples
c++winapiunicodeclipboardollydbg

Copy unicode string to clipboard isn't working


I don't know why this code isn't working properly:

#define UNICODE

#include <iostream>
#include <sstream>
#include <windows.h>

void main(void)
{
    wchar_t* strData = L"CreateWindowExA";

    MessageBox(NULL, strData, L"Warning", MB_OK);

    if (OpenClipboard(0)) {
        EmptyClipboard();
        HGLOBAL hClipboardData;
        hClipboardData = GlobalAlloc(GMEM_DDESHARE,
                                     wcslen(strData) + 1);
        char* pchData;
        pchData = (char*)GlobalLock(hClipboardData);
        strcpy(pchData, LPCSTR(strData));
        GlobalUnlock(hClipboardData);
        SetClipboardData(CF_TEXT, hClipboardData);
        CloseClipboard();
    }

    MessageBox(NULL, L"Copied to Clipboard", L"Title", MB_OK);
}

Solution

  • Change this section:

    hClipboardData = GlobalAlloc(GMEM_DDESHARE, sizeof(WCHAR) * (wcslen(strData) + 1));
    
    WCHAR* pchData;
    pchData = (WCHAR*)GlobalLock(hClipboardData);
    wcscpy(pchData, strData);
    GlobalUnlock(hClipboardData);
    SetClipboardData(CF_UNICODETEXT, hClipboardData);
    

    Allocate 2* number of bytes for WCHAR. Instead of char, use WCHAR. Instead of strcpy, use wcscpy. Instead of CF_TEXT, use CF_UNICODETEXT.