UiClipboard_Windows.cpp 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. /*
  2. * Copyright (c) Contributors to the Open 3D Engine Project.
  3. * For complete copyright and license terms please see the LICENSE at the root of this distribution.
  4. *
  5. * SPDX-License-Identifier: Apache-2.0 OR MIT
  6. *
  7. */
  8. // UiClipboard is responsible setting and getting clipboard data for the UI elements in a platform-independent way.
  9. #include "UiClipboard.h"
  10. #include <AzCore/PlatformIncl.h>
  11. #include <AzCore/std/string/conversions.h>
  12. bool UiClipboard::SetText(const AZStd::string& text)
  13. {
  14. bool success = false;
  15. if (OpenClipboard(nullptr))
  16. {
  17. if (EmptyClipboard())
  18. {
  19. if (text.length() > 0)
  20. {
  21. AZStd::wstring wstr;
  22. AZStd::to_wstring(wstr, text.c_str());
  23. const SIZE_T buffSize = (wstr.size() + 1) * sizeof(WCHAR);
  24. if (HGLOBAL hBuffer = GlobalAlloc(GMEM_MOVEABLE, buffSize))
  25. {
  26. auto buffer = static_cast<WCHAR*>(GlobalLock(hBuffer));
  27. memcpy_s(buffer, buffSize, wstr.data(), wstr.size() * sizeof(wchar_t));
  28. buffer[wstr.size()] = WCHAR(0);
  29. GlobalUnlock(hBuffer);
  30. SetClipboardData(CF_UNICODETEXT, hBuffer); // Clipboard now owns the hBuffer
  31. success = true;
  32. }
  33. }
  34. }
  35. CloseClipboard();
  36. }
  37. return success;
  38. }
  39. AZStd::string UiClipboard::GetText()
  40. {
  41. AZStd::string outText;
  42. if (OpenClipboard(nullptr))
  43. {
  44. if (HANDLE hText = GetClipboardData(CF_UNICODETEXT))
  45. {
  46. const WCHAR* text = static_cast<const WCHAR*>(GlobalLock(hText));
  47. AZStd::to_string(outText, text);
  48. GlobalUnlock(hText);
  49. }
  50. CloseClipboard();
  51. }
  52. return outText;
  53. }