19 private const int WmTouch = 0x0240;
20 private const int WmParentNotify = 0x0210;
21 private const int WmCreate = 0x0001;
22 private const int WmDestroy = 0x0002;
23 private const int WmNcDestroy = 0x0082;
24 private const uint TouchDown = 0x0002;
25 private const uint TouchUp = 0x0004;
27 private readonly Control _surface;
28 private readonly WinFormsTouchState _state =
new();
29 private readonly Dictionary<Control, TouchWindowHook> _hooks = [];
30 private readonly Dictionary<IntPtr, NativeChildHook> _nativeChildren = [];
31 private bool _refreshingNativeChildren;
32 private bool _disposed;
37 _surface = surface ??
throw new ArgumentNullException(nameof(surface));
39 if (_surface.InvokeRequired)
40 throw new InvalidOperationException(
"Initialize WinForms touch on the control's UI thread.");
43 _surface.SizeChanged += OnSurfaceSizeChanged;
44 RefreshNativeChildren();
58 (_hooks.Values.Any(
static hook => hook.IsRegistered) ||
59 _nativeChildren.Values.Any(
static hook => hook.IsRegistered));
65 internal static bool IsNativeTouchMouseMessage(Control surface)
68 !adapter.IsRegistered || !ReferenceEquals(adapter._surface, surface))
71 return WinFormsTouchState.IsPromotedTouchMouseMessage(GetMessageExtraInfo().ToInt64());
74 private void Watch(Control control)
76 if (_hooks.ContainsKey(control))
79 var hook =
new TouchWindowHook(
this, control);
80 _hooks.Add(control, hook);
81 control.ControlAdded += OnControlAdded;
82 control.ControlRemoved += OnControlRemoved;
84 foreach (Control child
in control.Controls)
88 private void Unwatch(Control control)
90 foreach (Control child
in control.Controls.Cast<Control>().ToArray())
93 control.ControlAdded -= OnControlAdded;
94 control.ControlRemoved -= OnControlRemoved;
96 if (_hooks.Remove(control, out TouchWindowHook? hook))
103 private void OnSurfaceSizeChanged(
object? sender, EventArgs e)
104 => RefreshNativeChildren();
106 private void OnControlAdded(
object? sender, ControlEventArgs e)
109 RefreshNativeChildren();
112 private void OnControlRemoved(
object? sender, ControlEventArgs e)
115 RefreshNativeChildren();
124 private void RefreshNativeChildren()
126 if (_disposed || !_surface.IsHandleCreated || _refreshingNativeChildren)
129 _refreshingNativeChildren =
true;
133 var descendants =
new HashSet<IntPtr>();
139 descendants.Add(hwnd);
144 var managedHandles = _hooks.Values
145 .Where(
static hook => hook.Handle != IntPtr.Zero)
146 .Select(
static hook => hook.Handle)
149 foreach (IntPtr hwnd
in _nativeChildren.Keys.ToArray())
151 if (descendants.Contains(hwnd) && !managedHandles.Contains(hwnd))
154 _nativeChildren.Remove(hwnd, out NativeChildHook? stale);
158 foreach (IntPtr hwnd
in descendants)
160 if (managedHandles.Contains(hwnd) || _nativeChildren.ContainsKey(hwnd))
163 _nativeChildren.Add(hwnd,
new NativeChildHook(
this, hwnd));
168 _refreshingNativeChildren =
false;
172 private void ForgetNativeChild(IntPtr hwnd)
174 if (_nativeChildren.Remove(hwnd, out NativeChildHook? hook))
180 private bool HandleTouchMessage(IntPtr wParam, IntPtr lParam)
182 int count = unchecked((ushort)(wParam.ToInt64() & 0xFFFF));
189 var inputs =
new TouchInput[count];
191 if (!GetTouchInputInfo(
195 Marshal.SizeOf<TouchInput>()))
198 foreach (TouchInput input
in inputs)
203 var physical =
new Point(
204 (
int)Math.Round(input.X / 100d),
205 (
int)Math.Round(input.Y / 100d));
207 Point local = _surface.PointToClient(physical);
209 Point position = _surface
switch
211 WinFormGpuRenderSurfaceControl gpu when gpu.Host is not
null =>
212 gpu.Adapter.AdapterPxToScreenPx(local),
213 WinFormBitmapRenderSurfaceControl bitmap when bitmap.Host is not
null =>
214 bitmap.Adapter.AdapterPxToScreenPx(local),
218 int id = unchecked((
int)input.Id);
220 if ((input.Flags & TouchDown) != 0)
221 _state.Begin(
id, position);
222 else if ((input.Flags & TouchUp) != 0)
223 _state.End(
id, position);
225 _state.Move(
id, position);
233 CloseTouchInputHandle(lParam);
244 _surface.SizeChanged -= OnSurfaceSizeChanged;
247 foreach (NativeChildHook hook
in _nativeChildren.Values.ToArray())
250 _nativeChildren.Clear();
254 private sealed class TouchWindowHook : NativeWindow, IDisposable
257 private readonly Control _control;
265 _control.HandleCreated += OnHandleCreated;
266 _control.HandleDestroyed += OnHandleDestroyed;
268 if (_control.IsHandleCreated)
272 private void OnHandleCreated(
object? sender, EventArgs e)
275 _owner.RefreshNativeChildren();
278 private void OnHandleDestroyed(
object? sender, EventArgs e)
281 _owner.RefreshNativeChildren();
282 _owner._state.CancelAll();
285 private void Attach()
287 if (Handle != IntPtr.Zero || !_control.IsHandleCreated)
290 AssignHandle(_control.Handle);
294 private void Detach()
296 if (Handle == IntPtr.Zero)
300 UnregisterTouchWindow(Handle);
302 IsRegistered =
false;
306 protected override void WndProc(ref Message m)
308 if (m.Msg == WmTouch && IsRegistered &&
309 _owner.HandleTouchMessage(m.WParam, m.LParam))
311 m.Result = IntPtr.Zero;
318 if (m.Msg == WmParentNotify &&
319 ((m.WParam.ToInt64() & 0xFFFF) is WmCreate or WmDestroy))
320 _owner.RefreshNativeChildren();
325 _control.HandleCreated -= OnHandleCreated;
326 _control.HandleDestroyed -= OnHandleDestroyed;
335 private sealed class NativeChildHook : NativeWindow, IDisposable
339 internal bool IsRegistered {
get;
private set; }
345 IsRegistered = RegisterTouchWindow(hwnd, 0);
348 protected override void WndProc(ref Message m)
350 if (m.Msg == WmTouch && IsRegistered &&
351 _owner.HandleTouchMessage(m.WParam, m.LParam))
353 m.Result = IntPtr.Zero;
357 IntPtr hwnd = Handle;
360 if (m.Msg == WmParentNotify &&
361 ((m.WParam.ToInt64() & 0xFFFF) is WmCreate or WmDestroy))
362 _owner.RefreshNativeChildren();
364 if (m.Msg == WmNcDestroy)
365 _owner.ForgetNativeChild(hwnd);
370 if (Handle == IntPtr.Zero)
374 UnregisterTouchWindow(Handle);
376 IsRegistered =
false;
382 [StructLayout(LayoutKind.Sequential)]
383 private struct TouchInput
387 internal IntPtr Source;
392 internal UIntPtr ExtraInfo;
393 internal uint ContactWidth;
394 internal uint ContactHeight;
397 private delegate
bool EnumWindowsCallback(IntPtr hwnd, IntPtr lParam);
399 [DllImport(
"user32.dll")]
400 [
return: MarshalAs(UnmanagedType.Bool)]
401 private static extern bool EnumChildWindows(
403 EnumWindowsCallback callback,
406 [DllImport(
"user32.dll", SetLastError =
true)]
407 [
return: MarshalAs(UnmanagedType.Bool)]
408 private static extern bool RegisterTouchWindow(IntPtr hwnd, uint flags);
410 [DllImport(
"user32.dll", SetLastError =
true)]
411 [
return: MarshalAs(UnmanagedType.Bool)]
412 private static extern bool UnregisterTouchWindow(IntPtr hwnd);
414 [DllImport(
"user32.dll", SetLastError =
true)]
415 [
return: MarshalAs(UnmanagedType.Bool)]
416 private static extern bool GetTouchInputInfo(
419 [Out] TouchInput[] inputs,
422 [DllImport(
"user32.dll")]
423 [
return: MarshalAs(UnmanagedType.Bool)]
424 private static extern bool CloseTouchInputHandle(IntPtr handle);
426 [DllImport(
"user32.dll")]
427 private static extern IntPtr GetMessageExtraInfo();