UTF-8 text to clipboard C

人盡茶涼 提交于 2019-12-12 17:07:02

问题


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:


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();


来源:https://stackoverflow.com/questions/37759292/utf-8-text-to-clipboard-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!