MFC中将EDIT控件或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();
}

下面很有可能是乱码

CString source;
if (OpenClipboard())
{
EmptyClipboard();

HGLOBAL clipbuffer = GlobalAlloc(GMEM_MOVEABLE,source.GetLength()+1);
if (!clipbuffer)
{
::CloseClipboard();
return;
}
char* buffer = (char*)::GlobalLock(clipbuffer);
strcpy_s(buffer,LPCTSTR(source));
::GlobalUnlock(clipbuffer);
::SetClipboardData(CF_UNICODETEXT,clipbuffer);
::CloseClipboard();
}

你可能感兴趣的:(VC++)