I tried to make a quick method to set the clipboard text in MFC, but this does not work.
void CopyTextToClipBoard( CString strText)
{
if (OpenClipboard(GetFrame()->GetSafeHwnd()))
{
EmptyClipboard() ;
SetClipboardData (CF_TEXT, strText.GetBuffer() ) ;
CloseClipboard () ;
}
}
I get a 'Windows breakpoint' error at 'setClipboardData'. Anyone know what I might have done wrong?
Edit: Thanks for your comment. Modfied. Now it fails at: memcopy function.
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 () ;
}
}
Edit: Using this old msdn example.
const char* output = "Test";
const size_t len = strlen(output) + 1;
HGLOBAL hMem = GlobalAlloc(GMEM_MOVEABLE, len);
memcpy(GlobalLock(hMem), output, len);
GlobalUnlock(hMem);
OpenClipboard(0);
EmptyClipboard();
SetClipboardData(CF_TEXT, hMem);
CloseClipboard();
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With