Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Copy text to Clipboard in MFC

Tags:

c++

mfc

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();
like image 484
netcat Avatar asked Dec 07 '22 22:12

netcat


1 Answers

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)

like image 120
Blacktempel Avatar answered Dec 15 '22 01:12

Blacktempel