代码如下:
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),开始笔者忘了,结果内存出错.
本文介绍了一个使用C++实现的复制到剪贴板的功能代码。该功能通过获取指定ID的对话框中的文本,并将其分配给剪贴板。文章特别强调了内存分配及释放的重要性,以及在操作过程中对内存大小的正确处理。
864

被折叠的 条评论
为什么被折叠?



