原本用的这个文字复制函数:
string ws2s(const wstring wstr)
{
string result;
size_t len = WideCharToMultiByte(CP_ACP, 0, wstr.c_str(),
(int)(wstr.size()), NULL, 0, NULL, NULL);
if (len <= 0)return result;
char* buffer = new char[len + 1];
if (buffer == NULL)return result;
WideCharToMultiByte(CP_ACP, 0, wstr.c_str(),
(int)(wstr.size()), buffer, (int)len, NULL, NULL);
buffer[len] = '\0';
result.append(buffer);
delete[] buffer;
return result;
}
wstring s2ws(const string str)
{
wstring result;
size_t len = MultiByteToWideChar(CP_ACP, 0, str.c_str(),
(int)(str.size()), NULL, 0);
if (len < 0)return result;
wchar_t* buffer = new wchar_t[len + 1];
if (buffer == NULL)return result;
MultiByteToWideChar(CP_ACP, 0, str.c_str(), (int)(str.size()),
buffer, (int)len);
buffer[len] = '\0';
result.append(buffer);
delete[] buffer;
return result;
}
//头文件
errno_t CopyText(const wstring& text, UINT uFormat = CF_UNICODETEXT);
inline errno_t CopyText(const string& text, UINT uFormat = CF_TEXT) {
return CopyText(s2ws(text), uFormat);
};
//源文件
errno_t CopyText(const wstring& text, UINT uFormat) {
if (!::OpenClipboard(NULL)) {
return 1;
}
if (!::EmptyClipboard()) {
if (!::CloseClipboard()) {
return 2;
}
return 3;
}
size_t tSize = (text.length() + 1) * sizeof(wchar_t);
HGLOBAL hMem = ::GlobalAlloc(GHND, tSize);
if (!hMem) {
if (!::CloseClipboard()) {
return 4;
}
return 5;
}
wchar_t* strText = (wchar_t*)calloc(tSize, 1);
//wcscpy_s(strText, tSize, text.c_str());
memcpy(strText, text.c_str(), tSize);
// 把数据拷贝到全局内存中
// 锁住内存区
LPWSTR lpStr = (LPWSTR)GlobalLock(hMem);
wchar_t* pMem = reinterpret_cast<wchar_t*>(lpStr);
if (!pMem) {
if (!::CloseClipboard()) {
return 6;
}
if ((!::GlobalUnlock(hMem)) && (GetLastError() != NO_ERROR)) {
return 7;
}
if (!::GlobalFree(hMem)) {
return 8;
}
return 9;
}
// 内存复制
::memcpy(lpStr, strText, tSize);
// 字符结束符: GMEM_ZEROINIT
if ((!::GlobalUnlock(hMem)) && (GetLastError() != NO_ERROR)) {
return 10;
}
HANDLE hResult = ::SetClipboardData(uFormat, hMem);
if (!::CloseClipboard()) {
return 11;
}
::free(strText);
if ((!hResult) || hResult == INVALID_HANDLE_VALUE) {
return 14;
}
return 0;
}
复制中文时没有出现问题,但是英文只能复制一个字符。。。
例如: 复制“复制”是没问题的,但复制“abc”只能得到“a”。
改了亿些细节后,发现是剪切板格式的锅:
inline errno_t CopyText(const string& text, UINT uFormat = CF_TEXT) {
return CopyText(s2ws(text), uFormat);
};
原本已经将文本转换为Unicode,但还在用ASCII格式表达,就会出问题 。。
解决方法:既然已经有转换格式,那么直接用CF_UNICODETEXT
errno_t CopyText(const wstring& text, UINT uFormat = CF_UNICODETEXT);
inline errno_t CopyText(const string& text, UINT uFormat = CF_UNICODETEXT) {
return CopyText(s2ws(text), uFormat);
};
完美解决。