Clipboard.cs 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. using NStack;
  2. using System;
  3. namespace Terminal.Gui {
  4. /// <summary>
  5. /// Provides cut, copy, and paste support for the clipboard with OS interaction.
  6. /// </summary>
  7. public static class Clipboard {
  8. static ustring contents;
  9. /// <summary>
  10. /// Get or sets the operation system clipboard, otherwise the contents field.
  11. /// </summary>
  12. public static ustring Contents {
  13. get {
  14. try {
  15. if (IsSupported) {
  16. return contents = ustring.Make (Application.Driver.Clipboard.GetClipboardData ());
  17. } else {
  18. return contents;
  19. }
  20. } catch (Exception) {
  21. return contents;
  22. }
  23. }
  24. set {
  25. try {
  26. if (IsSupported && value != null) {
  27. Application.Driver.Clipboard.SetClipboardData (value.ToString ());
  28. }
  29. contents = value;
  30. } catch (NotSupportedException e) {
  31. throw e;
  32. } catch (Exception) {
  33. contents = value;
  34. }
  35. }
  36. }
  37. /// <summary>
  38. /// Returns true if the environmental dependencies are in place to interact with the OS clipboard.
  39. /// </summary>
  40. public static bool IsSupported { get => Application.Driver.Clipboard.IsSupported; }
  41. /// <summary>
  42. /// Gets the operation system clipboard if possible.
  43. /// </summary>
  44. /// <param name="result">Clipboard contents read</param>
  45. /// <returns>true if it was possible to read the OS clipboard.</returns>
  46. public static bool TryGetClipboardData (out string result)
  47. {
  48. if (Application.Driver.Clipboard.TryGetClipboardData (out result)) {
  49. if (contents != result) {
  50. contents = result;
  51. }
  52. return true;
  53. }
  54. return false;
  55. }
  56. /// <summary>
  57. /// Sets the operation system clipboard if possible.
  58. /// </summary>
  59. /// <param name="text"></param>
  60. /// <returns>True if the clipboard content was set successfully.</returns>
  61. public static bool TrySetClipboardData (string text)
  62. {
  63. if (Application.Driver.Clipboard.TrySetClipboardData (text)) {
  64. contents = text;
  65. return true;
  66. }
  67. return false;
  68. }
  69. }
  70. }