-2

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.

  • 3
    C++ has no concept of a clipboard; this is specific to your OS and/or windowing layer. – MrEricSir Aug 12 '17 at 20:46
  • What do you mean by "like in any other program"? You can just press Ctrl+c everywhere. – ForceBru Aug 12 '17 at 20:46
  • I would suggest to take a look [HERE](https://stackoverflow.com/questions/6436257/how-do-you-copy-paste-from-the-clipboard-in-c). Clipboard is not easy as it seems, but it's not anything hard. Keep in mind you have to check the type of the copied data, because it can be text, images, custom/raw data, etc... – FonzTech Aug 12 '17 at 20:47

2 Answers2

5

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;
}
kocica
  • 6,412
  • 2
  • 14
  • 35
0

For a cross-platform solution, you may use a library like ClipboardXX.

Usage example:

#include "clipboard.hpp"
#include <string>

int main()
{
    clipboardxx::clipboard clipboard;

    // copy
    clipboard << "text you wanna copy";

    // paste
    std::string paste_text;
    clipboard >> paste_text;
}

This may be preferrable for a Windows only software as well due to modern C++ being nicer to work with than the plain old Windows API.

Another useful library might be clip but I didn't test it myself.

Usage example:

#include "clip.h"
#include <iostream>

int main()
{
  clip::set_text("Hello World");

  std::string value;
  clip::get_text(value);
  std::cout << value << "\n";
}
BullyWiiPlaza
  • 17,329
  • 10
  • 113
  • 185