Search code examples
c++clipboardcopy-paste

how to copy text to the clipborad in c++?


I am a new programmer in c++ and I can't understand how to use the clipboard to copy and paste like in any other program with text. Example please?

I am using Code::Blocks 16.01 MinGW32 g++ windows 10.


Solution

  • SetClipboardData should handle it.

    glob = GlobalAlloc(GMEM_FIXED,32);
    memcpy(glob,"it works",9);
    
    OpenClipboard(hWnd);
    EmptyClipboard();
    SetClipboardData(CF_TEXT,glob);
    CloseClipboard();
    

    EDIT

    This will get data out of clipboard and return that data in string.

    std::string GetClipboardText()
    {
        OpenClipboard(nullptr);
        HANDLE hData = GetClipboardData(CF_TEXT);
    
        char * pszText = static_cast<char*>( GlobalLock(hData) );
        std::string text( pszText );
    
        GlobalUnlock( hData );
        CloseClipboard();
    
        return text;
    }