拷贝字符串到Windows剪贴板

类别:VC语言 点击:0 评论:0 推荐:

// hWnd可以为NULL, lpszText为需要拷贝的字符串

BOOL CopyStringToClipboard(HWND hWnd, LPCTSTR lpszText)
{
 int nlen = strlen(lpszText);
 if (nlen == 0)
  return FALSE;

// 将szText中的内容复制到剪贴板
 HGLOBAL hglbCopy;
 LPTSTR  lptstrCopy;

 if (!::OpenClipboard(hWnd))
  return FALSE;

 hglbCopy = GlobalAlloc(GMEM_DDESHARE,
            (nlen + 1) * sizeof(char));
 
 if (hglbCopy == NULL)
 {
  CloseClipboard();
  return FALSE;
 }

 EmptyClipboard();

 lptstrCopy = (LPTSTR)GlobalLock(hglbCopy);
    memcpy(lptstrCopy, lpszText, nlen);
    lptstrCopy[nlen] = (TCHAR) 0;    // null character
    GlobalUnlock(lptstrCopy);
  
 SetClipboardData(CF_TEXT, hglbCopy);
 CloseClipboard();

 return TRUE;
}

本文地址:http://com.8s8s.com/it/it3345.htm