UTF-8 text to clipboard C

2019-07-09 00:30发布

I have been looking around on how to bring a string,

const char* output = "ヽ(⌐■_■)ノ♪♬";

to the clipboard.

SetClipboardData(CF_UNICODETEXT, hMem);

I have tried MultiByteToWideChar, but I have gotten only noise and also conflicting claims that you cannot save UTF-16LE to clipboard (wchar_t). Honestly I am just confused. A direction or code sample would be great.

1条回答
我只想做你的唯一
2楼-- · 2019-07-09 01:15

Windows uses UTF-16LE. The string should be created with L prefix. To use UTF8 you can declare the string with u8 prefix. For example:

const char* text = u8"ヽ(⌐■_■)ノ♪♬E";

Then you have to use MultiByteToWideChar to convert UTF8 to UTF16 and use in WinAPI. Note that to use u8 you need newer compilers like VS2015.

It's easier to use UTF16 in the first place. For example:

const wchar_t* text = L"ヽ(⌐■_■)ノ♪♬E";
int len = wcslen(text);

HGLOBAL hMem = GlobalAlloc(GMEM_MOVEABLE, (len + 1) * sizeof(wchar_t));
wchar_t* buffer = (wchar_t*)GlobalLock(hMem);
wcscpy_s(buffer, len + 1, text);
GlobalUnlock(hMem);

OpenClipboard(NULL);
EmptyClipboard();
SetClipboardData(CF_UNICODETEXT, hMem);
CloseClipboard();
查看更多
登录 后发表回答