我尝试使用快速方法在MFC中设置剪贴板文本,但这不起作用。
executable jar
我在'setClipboardData'上收到'Windows断点'错误。谁知道我可能做错了什么?
编辑:感谢您的评论。 Modfied。现在它失败了:memcopy功能。
void CopyTextToClipBoard( CString strText)
{
if (OpenClipboard(GetFrame()->GetSafeHwnd()))
{
EmptyClipboard() ;
SetClipboardData (CF_TEXT, strText.GetBuffer() ) ;
CloseClipboard () ;
}
}
编辑:使用这个旧的msdn示例。
void CopyTextToClipBoard( CString strText)
{
if (OpenClipboard(GetFrame()->GetSafeHwnd()))
{
HGLOBAL hglbCopy;
LPTSTR lptstrCopy;
hglbCopy = GlobalAlloc(GMEM_MOVEABLE, (strText.GetLength() + 1) * sizeof(TCHAR));
if (hglbCopy == NULL)
{
CloseClipboard();
return ;
}
memcpy(GlobalLock(hglbCopy), &strText, strText.GetLength() + 1 * sizeof(TCHAR));
GlobalUnlock(hglbCopy);
SetClipboardData(CF_TEXT, hglbCopy);
EmptyClipboard() ;
SetClipboardData (CF_TEXT, strText.GetBuffer() ) ;
CloseClipboard () ;
}
}
答案 0 :(得分:4)
来自SetClipboardData(uFormat,hMem)
的MSDN文档如果 hMem 参数标识内存对象,则该对象必须具有 使用带有 GMEM_MOVEABLE 标志
的函数进行分配
你可以这样做:
LPTSTR lptstrCopy;
HGLOBAL hglbCopy;
unsigned int strSize=strText.GetLength();//get your string lenght
hglbCopy = GlobalAlloc(GMEM_MOVEABLE, (strSize+1) * sizeof(TCHAR));//allocate the memory object with GMEM_MOVEABLE
if (hglbCopy == NULL)
{
CloseClipboard();
//other error handling
}
lptstrCopy = (LPTSTR)GlobalLock(hglbCopy);
memcpy(lptstrCopy, strText.GetBuffer(), strSize * sizeof(TCHAR)); //copy the text data
lptstrCopy[strSize] = (TCHAR) 0;//the null terminator
GlobalUnlock(hglbCopy);
EmptyClipboard() ;
SetClipboardData (CF_TEXT,hglbCopy);
CloseClipboard () ;
答案 1 :(得分:3)
SetClipboardData
的第二个参数是全局内存块的句柄。
请参阅 http://www.codeproject.com/Articles/2242/Using-the-Clipboard-Part-I-Transferring-Simple-Tex 有详细解释。
答案 2 :(得分:3)
This is a working one - unicode.
void CopyToClipboard(HWND owner, const std::wstring &w)
{
if (OpenClipboard(owner))
{
HGLOBAL hgClipBuffer = nullptr;
std::size_t sizeInWords = w.size() + 1;
std::size_t sizeInBytes = sizeInWords * sizeof(wchar_t);
hgClipBuffer = GlobalAlloc(GHND | GMEM_SHARE, sizeInBytes);
if (!hgClipBuffer)
{
CloseClipboard();
return;
}
wchar_t *wgClipBoardBuffer = static_cast<wchar_t*>(GlobalLock(hgClipBuffer));
wcscpy_s(wgClipBoardBuffer, sizeInWords, w.c_str());
GlobalUnlock(hgClipBuffer);
EmptyClipboard();
SetClipboardData(CF_UNICODETEXT, hgClipBuffer);
CloseClipboard();
}
}
(Should be correct, wrote on phone)