BPL BPL - 22 days ago 5
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)) {
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);
}

Answer

Change this section:

hClipboardData = GlobalAlloc(GMEM_DDESHARE, 2 * (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, WCHAR. Instead of strcpy, wcscpy. Instead of CF_TEXT, CF_UNICODETEXT.