VC非ASCII语言复制到剪切板乱码问题

今天遇到奇怪的现象,日文系统下在控件上按下Ctrl+C,再粘贴出来得到乱码,非得切换到日文输入法再进行粘贴不可.经过代码分析,得出结论是剪切板SetClipboardData()时自动内存转换惹的祸.这家伙默认状态下并不能识别双字节的字符.
所以修改的思路是,先统统转成宽字符,再按照宽字符进行拷贝.

之前的代码:

BOOL	CopyStringToClipBoard( HWND hOwner, CString strSource )
{
	if( ::OpenClipboard(hOwner) )
	{
		HANDLE clipbuffer ;
		char *buffer ;
		::EmptyClipboard() ;
		clipbuffer = ::GlobalAlloc( GMEM_DDESHARE,strSource.GetLength()+1 ) ;
		buffer = (char*)::GlobalLock(clipbuffer) ;
		strcpy( buffer, LPCSTR(strSource) ) ;
		::GlobalUnlock(clipbuffer) ;
		::SetClipboardData(CF_TEXT, clipbuffer) ;
		::CloseClipboard() ;
	} 
	return FALSE ;
}

修改之后的代码:

BOOL	CopyStringToClipBoard( HWND hOwner, CString strSource )
{
	if( ::OpenClipboard(hOwner) )
	{
		int buff_size = strSource.GetLength() ;
		CStringW strWide = CStringW(strSource);
		int nLen = strWide.GetLength();
		HANDLE clipbuffer ;
		char* buffer;
		::EmptyClipboard() ;
		clipbuffer = ::GlobalAlloc( GMEM_DDESHARE, (nLen + 1) * 2 ) ;
		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() ;
	} 
	return FALSE ;
}

已有2条评论

你好,新朋友。留言前请先填写昵称邮箱