Clipboard.cs 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  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 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 (Exception) {
  31. contents = value;
  32. }
  33. }
  34. }
  35. /// <summary>
  36. /// Returns true if the environmental dependencies are in place to interact with the OS clipboard.
  37. /// </summary>
  38. public static bool IsSupported { get; } = Application.Driver.Clipboard.IsSupported;
  39. /// <summary>
  40. /// Gets the operation system clipboard if possible.
  41. /// </summary>
  42. /// <param name="result">Clipboard contents read</param>
  43. /// <returns>true if it was possible to read the OS clipboard.</returns>
  44. public static bool TryGetClipboardData (out string result)
  45. {
  46. if (Application.Driver.Clipboard.TryGetClipboardData (out result)) {
  47. if (contents != result) {
  48. contents = result;
  49. }
  50. return true;
  51. }
  52. return false;
  53. }
  54. /// <summary>
  55. /// Sets the operation system clipboard if possible.
  56. /// </summary>
  57. /// <param name="text"></param>
  58. /// <returns>True if the clipboard content was set successfully.</returns>
  59. public static bool TrySetClipboardData (string text)
  60. {
  61. if (Application.Driver.Clipboard.TrySetClipboardData (text)) {
  62. contents = text;
  63. return true;
  64. }
  65. return false;
  66. }
  67. }
  68. }