tags:

views:

84

answers:

1

I was basic some code off this code, also mentioned in my other question. That version forces the character type to char*, which breaks compilation on my unicode project. So I made the following tweaks:

void SetClipboardText(CString & szData)
{
    HGLOBAL h;
    LPTSTR arr;

    size_t bytes = (szData.GetLength()+1)*sizeof(TCHAR);
    h=GlobalAlloc(GMEM_MOVEABLE, bytes);
    arr=(LPTSTR)GlobalLock(h);
    ZeroMemory(arr,bytes);
    _tcscpy_s(arr, szData.GetLength()+1, szData);
    szData.ReleaseBuffer();
    GlobalUnlock(h);

    ::OpenClipboard (NULL);
    EmptyClipboard();
    SetClipboardData(CF_TEXT, h);
    CloseClipboard();
}

The copying looks fine - running in a debugger Visual Studio tells me arr contains the copied string as expected. But When I then paste into any application, only the first character is pasted.

What's going wrong?

+2  A: 

Your Unicode comment in the prior question's comment is telling. If you have a wide character string with a low-ASCII character, in UTF-16 it's going to be encoded as the low-ASCII byte followed by a NULL. Use CF_UNICODETEXT instead of CF_TEXT.

Conspicuous Compiler
Good catch, I never thought of that 2nd-byte-is-zero case.
John