将字符串复制到剪贴板,粘贴时只写入一个字符 [英] Copying string to clipboard, only one character written when pasted
问题描述
我是这个代码的基本代码,也在我的另一个问题中提到.该版本强制字符类型为 char*
,这会破坏我的 unicode 项目的编译.所以我做了以下调整:
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();
}
复制看起来不错 - 在调试器中运行 Visual Studio 告诉我 arr
按预期包含复制的字符串.但是当我粘贴到任何应用程序时,只粘贴第一个字符.
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.
怎么了?
推荐答案
您在上一个问题的评论中的 Unicode 评论很有说服力.如果您有一个带有低 ASCII 字符的宽字符串,则在 UTF-16 中它将被编码为低 ASCII 字节后跟一个 NULL.使用 CF_UNICODETEXT 而不是 CF_TEXT.
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.
这篇关于将字符串复制到剪贴板,粘贴时只写入一个字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!