Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Public Discord: http://roleplay.FutureGadgetLab.net (Alaestor FGL 2017)
- #ifndef CLIPBOARDSTRING_H_INCLUDED
- #define CLIPBOARDSTRING_H_INCLUDED
- #define WINVER _WIN32_WINNT_WIN7
- #include <exception>
- #include <string>
- #include <windows.h>
- // warning: after use, must be destroyed as soon as possible.
- // has exclusive clipboard access for lifetime of object.
- class ClipboardString
- {
- private:
- auto initData() const
- {
- if (!OpenClipboard(nullptr)) throw std::runtime_error(
- "ClipboardData::initData() OpenClipboard() failed");
- const auto& cbd = GetClipboardData(CF_UNICODETEXT);
- if (cbd == nullptr) throw std::runtime_error(
- "ClipboardData::initData() GetClipboardData() failed");
- return cbd;
- }
- const HANDLE m_data;
- public:
- const std::wstring get() const
- {return std::wstring(reinterpret_cast< wchar_t* >(m_data));}
- void set(const std::wstring& wstr)
- {
- EmptyClipboard();
- const std::size_t size = (wstr.size() + 1) * sizeof(wstr[0]);
- const auto& handle = GlobalAlloc(GMEM_MOVEABLE, size);
- if (handle == nullptr) throw std::runtime_error(
- "ClipboardData::set() GlobalAlloc() failed");
- const auto& ptr = GlobalLock(handle);
- if (ptr == nullptr) throw std::runtime_error(
- "ClipboardData::set() GlobalLock() failed");
- memcpy(ptr, wstr.data(), size);
- GlobalUnlock(handle);
- const auto& result = SetClipboardData(CF_UNICODETEXT, handle);
- if (result == nullptr) throw std::runtime_error(
- "ClipboardData::set() SetClipboardData() failed");
- }
- void set(const std::string& str)
- { // converts to wstring, does temp allocation
- std::wstring wstr(str.length(), L' ');
- std::copy(str.cbegin(), str.cend(), wstr.begin());
- set(wstr);
- }
- explicit ClipboardString() :
- m_data(initData())
- {}
- ~ClipboardString()
- { CloseClipboard(); }
- };
- #endif // CLIPBOARDSTRING_H_INCLUDED
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement