/src/StylusReader/StylusReader.cs
C# | 89 lines | 67 code | 13 blank | 9 comment | 4 complexity | 64275745ae4c75f081f2a913aedc50f9 MD5 | raw file
- /////////////////////////////////////////////////////////////////////////////////
- // Paint.NET //
- // Copyright (C) dotPDN LLC, Rick Brewster, Tom Jackson, and contributors. //
- // Portions Copyright (C) Microsoft Corporation. All Rights Reserved. //
- // See src/Resources/Files/License.txt for full licensing and attribution //
- // details. //
- // . //
- /////////////////////////////////////////////////////////////////////////////////
-
- using Microsoft.Ink;
- using Microsoft.StylusInput;
- using System;
- using System.Collections;
- using System.Collections.Generic;
- using System.Windows.Forms;
-
- namespace PaintDotNet
- {
- public static class StylusReader
- {
- // If we don't keep the styluses, they get garbagecollected.
- private static readonly Hashtable HookedControls = Hashtable.Synchronized(new Hashtable());
-
- public static void HookStylus(IStylusReaderHooks subject, Control control)
- {
- if (HookedControls.Contains(control))
- {
- throw new ApplicationException("control is already hooked");
- }
-
- var stylus = new RealTimeStylus(control, true);
- var stylusReader = new StylusAsyncPlugin(subject, control);
-
- stylus.AsyncPluginCollection.Add(stylusReader);
- stylus.SetDesiredPacketDescription(new[] { PacketProperty.X,
- PacketProperty.Y,
- PacketProperty.NormalPressure,
- PacketProperty.PacketStatus});
- stylus.Enabled = true;
-
- control.Disposed += ControlDisposed;
-
- var weakRef = new WeakReference(control);
- HookedControls.Add(weakRef, stylus);
- }
-
- public static void UnhookStylus(Control control)
- {
- lock (HookedControls.SyncRoot)
- {
- var deleteUs = new List<WeakReference>();
-
- foreach (WeakReference weakRef in HookedControls.Keys)
- {
- object target = weakRef.Target;
-
- if (target == null)
- {
- deleteUs.Add(weakRef);
- }
- else
- {
- var control2 = (Control)target;
-
- if (ReferenceEquals(control, control2))
- {
- deleteUs.Add(weakRef);
- }
- }
- }
-
- foreach (WeakReference weakRef in deleteUs)
- {
- var stylus = (RealTimeStylus)HookedControls[weakRef];
- stylus.Enabled = false;
- stylus.AsyncPluginCollection.Clear();
- HookedControls.Remove(weakRef);
- }
- }
- }
-
- private static void ControlDisposed(object sender, EventArgs e)
- {
- var asControl = (Control)sender;
- asControl.Disposed -= ControlDisposed;
- UnhookStylus(asControl);
- }
- }
- }