tb_clipboard_win.cpp 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. // ================================================================================
  2. // == This file is a part of Turbo Badger. (C) 2011-2014, Emil Segerås ==
  3. // == See tb_core.h for more information. ==
  4. // ================================================================================
  5. #include "tb_system.h"
  6. #ifdef TB_CLIPBOARD_WINDOWS
  7. #include <Windows.h>
  8. #include <stdio.h>
  9. namespace tb {
  10. // == TBClipboard =====================================
  11. void TBClipboard::Empty()
  12. {
  13. if (OpenClipboard(NULL))
  14. {
  15. EmptyClipboard();
  16. CloseClipboard();
  17. }
  18. }
  19. bool TBClipboard::HasText()
  20. {
  21. bool has_text = false;
  22. if (OpenClipboard(NULL))
  23. {
  24. has_text = IsClipboardFormatAvailable(CF_TEXT) ||
  25. IsClipboardFormatAvailable(CF_OEMTEXT) ||
  26. IsClipboardFormatAvailable(CF_UNICODETEXT);
  27. CloseClipboard();
  28. }
  29. return has_text;
  30. }
  31. bool TBClipboard::SetText(const char *text)
  32. {
  33. if (OpenClipboard(NULL))
  34. {
  35. int num_wide_chars_needed = MultiByteToWideChar(CP_UTF8, 0, text, -1, NULL, 0);
  36. if (HGLOBAL hClipboardData = GlobalAlloc(GMEM_DDESHARE, num_wide_chars_needed * sizeof(wchar_t)))
  37. {
  38. LPWSTR pchData = (LPWSTR) GlobalLock(hClipboardData);
  39. MultiByteToWideChar(CP_UTF8, 0, text, -1, pchData, num_wide_chars_needed);
  40. GlobalUnlock(hClipboardData);
  41. EmptyClipboard();
  42. SetClipboardData(CF_UNICODETEXT, hClipboardData);
  43. }
  44. CloseClipboard();
  45. return true;
  46. }
  47. return false;
  48. }
  49. bool TBClipboard::GetText(TBStr &text)
  50. {
  51. bool success = false;
  52. if (HasText() && OpenClipboard(NULL))
  53. {
  54. if (HANDLE hClipboardData = GetClipboardData(CF_UNICODETEXT))
  55. {
  56. wchar_t *pchData = (wchar_t*) GlobalLock(hClipboardData);
  57. int len = WideCharToMultiByte(CP_UTF8, 0, pchData, -1, NULL, 0, NULL, NULL);
  58. if (char *utf8 = new char[len])
  59. {
  60. WideCharToMultiByte(CP_UTF8, 0, pchData, -1, utf8, len, NULL, NULL);
  61. success = text.Set(utf8);
  62. delete [] utf8;
  63. }
  64. GlobalUnlock(hClipboardData);
  65. }
  66. CloseClipboard();
  67. }
  68. return success;
  69. }
  70. }; // namespace tb
  71. #endif // TB_CLIPBOARD_WINDOWS