MacOSTextBoxFactory.cs 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. using System;
  2. using Avalonia.Platform;
  3. using Avalonia.Threading;
  4. using MonoMac.AppKit;
  5. using MonoMac.Foundation;
  6. namespace IntegrationTestApp.Embedding;
  7. internal class MacOSTextBoxFactory : INativeTextBoxFactory
  8. {
  9. public INativeTextBoxImpl CreateControl(IPlatformHandle parent)
  10. {
  11. MacHelper.EnsureInitialized();
  12. return new MacOSTextBox();
  13. }
  14. private class MacOSTextBox : NSTextView, INativeTextBoxImpl
  15. {
  16. private DispatcherTimer _timer;
  17. public MacOSTextBox()
  18. {
  19. TextStorage.Append(new("Native text box"));
  20. Handle = new MacOSViewHandle(this);
  21. _timer = new DispatcherTimer();
  22. _timer.Interval = TimeSpan.FromMilliseconds(400);
  23. _timer.Tick += (_, _) =>
  24. {
  25. Hovered?.Invoke(this, EventArgs.Empty);
  26. _timer.Stop();
  27. };
  28. }
  29. public new IPlatformHandle Handle { get; }
  30. public string Text
  31. {
  32. get => TextStorage.Value;
  33. set => TextStorage.Replace(new NSRange(0, TextStorage.Length), value);
  34. }
  35. public event EventHandler? ContextMenuRequested;
  36. public event EventHandler? Hovered;
  37. public event EventHandler? PointerExited;
  38. public override void MouseEntered(NSEvent theEvent)
  39. {
  40. _timer.Stop();
  41. _timer.Start();
  42. base.MouseEntered(theEvent);
  43. }
  44. public override void MouseExited(NSEvent theEvent)
  45. {
  46. _timer.Stop();
  47. PointerExited?.Invoke(this, EventArgs.Empty);
  48. base.MouseExited(theEvent);
  49. }
  50. public override void MouseMoved(NSEvent theEvent)
  51. {
  52. _timer.Stop();
  53. _timer.Start();
  54. base.MouseMoved(theEvent);
  55. }
  56. public override void RightMouseDown(NSEvent theEvent)
  57. {
  58. ContextMenuRequested?.Invoke(this, EventArgs.Empty);
  59. }
  60. public override void RightMouseUp(NSEvent theEvent)
  61. {
  62. // Don't call base to prevent default action.
  63. }
  64. }
  65. }