Advertisement
alaestor

[FGL Utility] ClipboardString.h

Oct 12th, 2017
258
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.86 KB | None | 0 0
  1. // Public Discord: http://roleplay.FutureGadgetLab.net (Alaestor FGL 2017)
  2. #ifndef CLIPBOARDSTRING_H_INCLUDED
  3. #define CLIPBOARDSTRING_H_INCLUDED
  4. #define WINVER _WIN32_WINNT_WIN7
  5. #include <exception>
  6. #include <string>
  7. #include <windows.h>
  8.  
  9.  
  10.  
  11. // warning: after use, must be destroyed as soon as possible.
  12. // has exclusive clipboard access for lifetime of object.
  13.  
  14.  
  15.  
  16. class ClipboardString
  17. {
  18.     private:
  19.  
  20.     auto initData() const
  21.     {
  22.         if (!OpenClipboard(nullptr)) throw std::runtime_error(
  23.             "ClipboardData::initData() OpenClipboard() failed");
  24.  
  25.         const auto& cbd = GetClipboardData(CF_UNICODETEXT);
  26.         if (cbd == nullptr) throw std::runtime_error(
  27.             "ClipboardData::initData() GetClipboardData() failed");
  28.  
  29.         return cbd;
  30.     }
  31.  
  32.     const HANDLE m_data;
  33.  
  34.     public:
  35.  
  36.     const std::wstring get() const
  37.     {return std::wstring(reinterpret_cast< wchar_t* >(m_data));}
  38.  
  39.     void set(const std::wstring& wstr)
  40.     {
  41.         EmptyClipboard();
  42.         const std::size_t size = (wstr.size() + 1) * sizeof(wstr[0]);
  43.         const auto& handle = GlobalAlloc(GMEM_MOVEABLE, size);
  44.         if (handle == nullptr) throw std::runtime_error(
  45.             "ClipboardData::set() GlobalAlloc() failed");
  46.  
  47.         const auto& ptr = GlobalLock(handle);
  48.         if (ptr == nullptr) throw std::runtime_error(
  49.             "ClipboardData::set() GlobalLock() failed");
  50.  
  51.         memcpy(ptr, wstr.data(), size);
  52.         GlobalUnlock(handle);
  53.  
  54.         const auto& result = SetClipboardData(CF_UNICODETEXT, handle);
  55.         if (result == nullptr) throw std::runtime_error(
  56.             "ClipboardData::set() SetClipboardData() failed");
  57.     }
  58.  
  59.     void set(const std::string& str)
  60.     { // converts to wstring, does temp allocation
  61.         std::wstring wstr(str.length(), L' ');
  62.         std::copy(str.cbegin(), str.cend(), wstr.begin());
  63.         set(wstr);
  64.     }
  65.  
  66.     explicit ClipboardString() :
  67.         m_data(initData())
  68.     {}
  69.  
  70.     ~ClipboardString()
  71.     { CloseClipboard(); }
  72. };
  73.  
  74. #endif // CLIPBOARDSTRING_H_INCLUDED
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement