BPL BPL - 9 months ago 50
C++ Question

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)) {
HGLOBAL hClipboardData;
hClipboardData = GlobalAlloc(GMEM_DDESHARE,
wcslen(strData) + 1);
char* pchData;
pchData = (char*)GlobalLock(hClipboardData);
strcpy(pchData, LPCSTR(strData));
SetClipboardData(CF_TEXT, hClipboardData);

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

Answer Source

Change this section:

hClipboardData = GlobalAlloc(GMEM_DDESHARE, 2 * (wcslen(strData) + 1));

WCHAR* pchData;
pchData = (WCHAR*)GlobalLock(hClipboardData);
wcscpy(pchData, strData);
SetClipboardData(CF_UNICODETEXT, hClipboardData);

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