Click here to Skip to main content
15,889,992 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Hi,

I'm trying to put Unicode UTF-8 data directly onto the Windows clipboard. Why does this not work:

C++
HGLOBAL hGlobal = GlobalAlloc(GMEM_MOVEABLE | GMEM_ZEROINIT, 16);
unsigned char *px = (unsigned char*) GlobalLock(hGlobal);
//a 3 byte UTF-8 character:
px[0] = 0xe0;
px[1] = 0xa0;
px[2] = 0xb0;
px[3] = 0x00;
OpenClipboard(hWnd);
EmptyClipboard();
GlobalUnlock(hGlobal);
SetClipboardData(CF_UNICODETEXT, px);
CloseClipboard();


Data always seems to go on the Clipboard as UTF-16, ie 2 bytes per code.

Any suggestions how I can achieve?

regards,

geoff
Posted
Updated 1-Oct-11 11:48am
v2

1 solution

CF_UNICODETEXT states that the data you're passing is a Unicode text, which is 2 bytes per character.
UTF-8 is multibyte per character.
They are not the same.

Convert your UTF-8 text to Unicode first, or use CF_TEXT instead.
 
Share this answer
 
v2
Comments
geoff7 2-Oct-11 5:06am    
CF_TEXT will not works as it interpretes the bytes as ANSI text and stops at the first null byte. I've tried WideCharToMultibyte (there are a few code examples on the net) but I still get the data as UTF-16. My input data is 0xeo, 0xa0, 0xbo which is a 3 byte UFT-8 and I need to put that character on the clipboard.
If CF_UTF_8 existed (!) I suppose it would be easy.
Chuck O'Toole 2-Oct-11 6:14am    
I deleted my comment, it didn't make a lot of sense after I re-read it a few times. If I couldn't understand what I wrote myself, I'm not sure anyone else would have. Sorry about that.
Ray Radin 2-Oct-11 7:55am    
If you want to use CF_UNICODETEXT, you need MultiByteToWideChar to convert UTF-8 to Unicode.
Not WideCharToMultiByte.

It works.
Give it a try.

There is no need for CF_UTF_8.
ANSI 0x00 is identical to UTF-8 0x00.
Any UTF-8 text can be treated as ANSI without a problem, but only for storage purpose.
For display purpose, you need to convert it to Unicode.
geoff7 2-Oct-11 15:17pm    
Thanks it works! I had the functions wrong as you stated!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900