Copy string to clipboard in C++

This is a simple code for understanding how to copy string to clipboard in Cpp

#include <conio.h>
#include <iostream>
#include <Windows.h>

void SetClipboard(char *);

void main()
{
    using namespace std;
    char i[128];
    cout << ">> ";
    gets(i);
    SetClipboard(i);
    cout << "\n\'" << i << "\' Copied to clipboard" << endl;
    getch();
}

void SetClipboard(char *output)
{
    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();
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s