Skip to content

Instantly share code, notes, and snippets.

@cameronism
Created August 4, 2020 04:30
Show Gist options
  • Save cameronism/7af669ecb7277ca3299e9f3e687486e3 to your computer and use it in GitHub Desktop.
Save cameronism/7af669ecb7277ca3299e9f3e687486e3 to your computer and use it in GitHub Desktop.
#include <iostream>
#include <Windows.h>
#include <string>
#include <codecvt>
// https://stackoverflow.com/questions/14762456/getclipboarddatacf-text
std::wstring GetClipboardText()
{
// Try opening the clipboard
if (!OpenClipboard(nullptr))
return L"";
// Get handle of clipboard object for ANSI text
HANDLE hData = GetClipboardData(CF_UNICODETEXT);
if (hData == nullptr)
return L"";
// Lock the handle to get the actual text pointer
wchar_t* pszText = static_cast<wchar_t*>(GlobalLock(hData));
if (pszText == nullptr)
return L"";
// Save text in a string class instance
std::wstring text(pszText);
// Release the lock
GlobalUnlock(hData);
// Release the clipboard
CloseClipboard();
return text;
}
int main()
{
SetConsoleOutputCP(CP_UTF8);
setvbuf(stdout, nullptr, _IOFBF, 1000);
std::wstring data = GetClipboardText();
std::wstring_convert<std::codecvt_utf8<wchar_t>> uutf8;
std::cout << uutf8.to_bytes(data) << std::endl;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment