// 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;
}