现在的位置: 首页 > 综合 > 正文

UNICODE版本的clipboard复制

2012年08月28日 ⁄ 综合 ⁄ 共 1061字 ⁄ 字号 评论关闭

代码如下:

void CJMMtnKeyDlg::OnBtnCopy()
{
 CString strResult;
 GetDlgItemText(IDC_PWD_OUT,strResult);
 if (strResult.GetLength() <= 0)
 {
  return;
 } 
 if (OpenClipboard())
 {
  HGLOBAL hClipboardData = GlobalAlloc(GMEM_MOVEABLE, (strResult.GetLength() + 1)* sizeof(TCHAR));
  if (hClipboardData == NULL)
  {
   CloseClipboard();
   return;
  }
  EmptyClipboard();
  LPTSTR lptstr = (LPTSTR)GlobalLock(hClipboardData);
  memcpy(lptstr, strResult.GetBuffer(0), strResult.GetLength() * sizeof(TCHAR));
  lptstr[strResult.GetLength()] = (TCHAR)0;  
  GlobalUnlock(hClipboardData);
  
  SetClipboardData(CF_UNICODETEXT, hClipboardData);

  //bool b  = IsClipboardFormatAvailable(CF_UNICODETEXT);
  CloseClipboard();
 }
}

 

笔者验证成功.

特别注意

HGLOBAL hClipboardData = GlobalAlloc(GMEM_MOVEABLE, (strResult.GetLength() + 1)* sizeof(TCHAR));

GMEM_MOVEABLE Allocates movable memory. In Win32, memory blocks are never moved in physical memory, but they can be moved within the default heap.

The return value is a handle to the memory object. To translate the handle into a pointer, use the GlobalLock function.

This flag cannot be combined with the GMEM_FIXED flag.

还有长度要*sizeof(TCHAR),开始笔者忘了,结果内存出错.

抱歉!评论已关闭.