PageRenderTime 49ms CodeModel.GetById 22ms RepoModel.GetById 1ms app.codeStats 0ms

/src/StylusReader/StylusReader.cs

https://bitbucket.org/tuldok89/openpdn
C# | 89 lines | 67 code | 13 blank | 9 comment | 4 complexity | 64275745ae4c75f081f2a913aedc50f9 MD5 | raw file
  1. /////////////////////////////////////////////////////////////////////////////////
  2. // Paint.NET //
  3. // Copyright (C) dotPDN LLC, Rick Brewster, Tom Jackson, and contributors. //
  4. // Portions Copyright (C) Microsoft Corporation. All Rights Reserved. //
  5. // See src/Resources/Files/License.txt for full licensing and attribution //
  6. // details. //
  7. // . //
  8. /////////////////////////////////////////////////////////////////////////////////
  9. using Microsoft.Ink;
  10. using Microsoft.StylusInput;
  11. using System;
  12. using System.Collections;
  13. using System.Collections.Generic;
  14. using System.Windows.Forms;
  15. namespace PaintDotNet
  16. {
  17. public static class StylusReader
  18. {
  19. // If we don't keep the styluses, they get garbagecollected.
  20. private static readonly Hashtable HookedControls = Hashtable.Synchronized(new Hashtable());
  21. public static void HookStylus(IStylusReaderHooks subject, Control control)
  22. {
  23. if (HookedControls.Contains(control))
  24. {
  25. throw new ApplicationException("control is already hooked");
  26. }
  27. var stylus = new RealTimeStylus(control, true);
  28. var stylusReader = new StylusAsyncPlugin(subject, control);
  29. stylus.AsyncPluginCollection.Add(stylusReader);
  30. stylus.SetDesiredPacketDescription(new[] { PacketProperty.X,
  31. PacketProperty.Y,
  32. PacketProperty.NormalPressure,
  33. PacketProperty.PacketStatus});
  34. stylus.Enabled = true;
  35. control.Disposed += ControlDisposed;
  36. var weakRef = new WeakReference(control);
  37. HookedControls.Add(weakRef, stylus);
  38. }
  39. public static void UnhookStylus(Control control)
  40. {
  41. lock (HookedControls.SyncRoot)
  42. {
  43. var deleteUs = new List<WeakReference>();
  44. foreach (WeakReference weakRef in HookedControls.Keys)
  45. {
  46. object target = weakRef.Target;
  47. if (target == null)
  48. {
  49. deleteUs.Add(weakRef);
  50. }
  51. else
  52. {
  53. var control2 = (Control)target;
  54. if (ReferenceEquals(control, control2))
  55. {
  56. deleteUs.Add(weakRef);
  57. }
  58. }
  59. }
  60. foreach (WeakReference weakRef in deleteUs)
  61. {
  62. var stylus = (RealTimeStylus)HookedControls[weakRef];
  63. stylus.Enabled = false;
  64. stylus.AsyncPluginCollection.Clear();
  65. HookedControls.Remove(weakRef);
  66. }
  67. }
  68. }
  69. private static void ControlDisposed(object sender, EventArgs e)
  70. {
  71. var asControl = (Control)sender;
  72. asControl.Disposed -= ControlDisposed;
  73. UnhookStylus(asControl);
  74. }
  75. }
  76. }