唐天宇 发表于 2023-6-23 13:54:30

C++ 将cstring内容复制到剪贴板




网上好多教程讲如何复制到剪贴板,但是有可能复制的是乱码,为了方便,将CString类型的复制到剪贴板。

CString source;
if (OpenClipboard())
{
//防止非ASCII语言复制到剪切板为乱码
int buff_size = source.GetLength();
CStringW strWide = CStringW(source);
int nLen = strWide.GetLength();
//将剪切板置空
::EmptyClipboard();
HANDLE clipbuffer = ::GlobalAlloc(GMEM_DDESHARE,(nLen+1)*2);
if (!clipbuffer)
{
::CloseClipboard();
return;
}
char* buffer = (char*)::GlobalLock(clipbuffer);
memset(buffer,0,(nLen+1)*2);
memcpy_s(buffer,nLen*2,strWide.GetBuffer(0),nLen*2);
strWide.ReleaseBuffer();
::GlobalUnlock(clipbuffer);
::SetClipboardData(CF_UNICODETEXT,clipbuffer);
::CloseClipboard();
}

页: [1]
查看完整版本: C++ 将cstring内容复制到剪贴板