Click here to Skip to main content
11,805,266 members (51,484 online)
Rate this: bad
Please Sign up or sign in to vote.
See more: C++ Windows clipboard

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

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;
SetClipboardData(CF_UNICODETEXT, px);

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

Any suggestions how I can achieve?


Posted 1-Oct-11 10:25am
Edited 1-Oct-11 11:48am

1 solution

Rate this: bad
Please Sign up or sign in to vote.

Solution 1

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.
geoff7 at 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 at 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.
RRadin at 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 at 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)

  Print Answers RSS
0 OriginalGriff 315
1 Richard Deeming 200
2 Sergey Alexandrovich Kryukov 170
3 CPallini 160
4 CHill60 150
0 OriginalGriff 3,255
1 Maciej Los 1,990
2 KrunalRohit 1,907
3 CPallini 1,855
4 Richard MacCutchan 1,227

Advertise | Privacy | Mobile
Web03 | 2.8.151002.1 | Last Updated 2 Oct 2011
Copyright © CodeProject, 1999-2015
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100