using Microsoft.UI.Windowing; using Microsoft.UI.Xaml.Input; using Microsoft.UI.Xaml.Media; using Microsoft.UI.Xaml.Media.Imaging; using Microsoft.UI.Xaml.Shapes; using System.Runtime.InteropServices.WindowsRuntime; using System.Runtime.InteropServices; using Windows.Foundation; using Windows.Graphics; using Windows.System; using XFEWorkflow.Abstractions; using XFEWorkflow.Plugins.Vision; namespace XFEWorkflow.Controls; /// A frozen, physical-pixel desktop overlay. It never sends input to other applications. internal sealed class ScreenRegionPicker { private readonly Window window = new() { Title = "框选识别区域" }; private readonly Canvas surface = new() { IsTabStop = true }; private readonly Rectangle selection = new() { StrokeThickness = 2, Fill = new SolidColorBrush(Windows.UI.Color.FromArgb(12, 255, 255, 255)), IsHitTestVisible = false }; private readonly Rectangle[] shade = Enumerable.Range(0, 4).Select(_ => new Rectangle { Fill = new SolidColorBrush(Windows.UI.Color.FromArgb(130, 0, 0, 0)), IsHitTestVisible = false }).ToArray(); private readonly TextBlock label = new() { Text = "拖动框选识别区域 · Enter 确认 · Esc 取消", Foreground = new SolidColorBrush(Microsoft.UI.Colors.White), FontSize = 14, TextWrapping = TextWrapping.Wrap }; private readonly Border instructions; private readonly Button confirm = new() { Content = "使用此区域", IsEnabled = false }; private readonly TaskCompletionSource completed = new(TaskCreationOptions.RunContinuationsAsynchronously); private readonly ScreenRegion bounds; private readonly bool pointMode; private readonly bool templateMode; private Point? start; private ulong dragTimestamp; private uint dragPointer; private ScreenRegion? current; internal FrameworkElement Root => surface; internal ScreenRegion? SelectedRegion => current; private ScreenRegionPicker(ScreenRegion bounds, bool pointMode = false, bool templateMode = false) { this.bounds = bounds; this.pointMode = pointMode; this.templateMode = templateMode; if (templateMode) { window.Title = "框选找图模板"; confirm.Content = "使用此模板"; } surface.Background = new SolidColorBrush(Microsoft.UI.Colors.Black); window.Content = surface; if (window.AppWindow.Presenter is OverlappedPresenter presenter) { presenter.SetBorderAndTitleBar(false, false); presenter.IsResizable = false; presenter.IsMinimizable = false; presenter.IsMaximizable = false; presenter.IsAlwaysOnTop = true; } PositionClient(new RectInt32(bounds.X, bounds.Y, bounds.Width, bounds.Height)); selection.Stroke = (Brush)Application.Current.Resources["AccentFillColorDefaultBrush"]; foreach (var rect in shade) surface.Children.Add(rect); surface.Children.Add(selection); var cancel = new Button { Content = "取消" }; cancel.Click += (_, _) => Complete(null); confirm.Click += (_, _) => { if (current is { } value) Complete(value); }; var buttons = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 8, HorizontalAlignment = HorizontalAlignment.Right, Children = { cancel, confirm } }; instructions = new Border { Background = new SolidColorBrush(Windows.UI.Color.FromArgb(240, 32, 32, 32)), CornerRadius = new(8), Padding = new(16), MaxWidth = 500, Child = new StackPanel { Spacing = 12, Children = { label, buttons } }, RequestedTheme = ElementTheme.Dark }; confirm.Style = (Style)Application.Current.Resources["AccentButtonStyle"]; surface.Children.Add(instructions); instructions.SizeChanged += (_, _) => UpdateVisual(); surface.SizeChanged += (_, _) => UpdateVisual(); surface.PointerPressed += Pressed; surface.PointerMoved += Moved; surface.PointerReleased += Released; surface.PointerCaptureLost += (_, e) => { if (!ReferenceEquals(e.OriginalSource, surface) || !IsCurrentDrag(e)) return; // Capture-lost events from an earlier window/gesture can arrive // after this press. Never cancel a newer drag with an older event. start = null; }; surface.PointerCanceled += (_, e) => { if (IsCurrentDrag(e)) start = null; }; window.Activated += (_, e) => { if (e.WindowActivationState == WindowActivationState.Deactivated && GetForegroundWindow() != WinRT.Interop.WindowNative.GetWindowHandle(window)) start = null; }; surface.KeyDown += (_, e) => { if (e.Key == VirtualKey.Escape) { e.Handled = true; Complete(null); } else if (e.Key == VirtualKey.Enter && current is { } region) { e.Handled = true; Complete(region); } }; window.Closed += (_, _) => completed.TrySetResult(null); } private void Pressed(object sender, PointerRoutedEventArgs e) { if (!e.GetCurrentPoint(surface).Properties.IsLeftButtonPressed || IsInInstructions(e.GetCurrentPoint(surface).Position)) return; // Focus can release an existing capture (for example after a dialog). // Establish focus before starting and capturing the new drag. surface.Focus(FocusState.Programmatic); var point = e.GetCurrentPoint(surface); start = point.Position; dragTimestamp = point.Timestamp; dragPointer = e.Pointer.PointerId; current = null; confirm.IsEnabled = false; surface.CapturePointer(e.Pointer); e.Handled = true; UpdateVisual(); } private bool IsInInstructions(Point point) => point.X >= Canvas.GetLeft(instructions) && point.X <= Canvas.GetLeft(instructions) + instructions.ActualWidth && point.Y >= Canvas.GetTop(instructions) && point.Y <= Canvas.GetTop(instructions) + instructions.ActualHeight; private bool IsCurrentDrag(PointerRoutedEventArgs e) => start is not null && e.Pointer.PointerId == dragPointer && e.GetCurrentPoint(surface).Timestamp >= dragTimestamp; private void Moved(object sender, PointerRoutedEventArgs e) { if (!IsCurrentDrag(e)) return; if (!e.GetCurrentPoint(surface).Properties.IsLeftButtonPressed) { start = null; return; } DragTo(e.GetCurrentPoint(surface).Position); e.Handled = true; } private void Released(object sender, PointerRoutedEventArgs e) { if (!IsCurrentDrag(e)) return; DragTo(e.GetCurrentPoint(surface).Position); start = null; surface.ReleasePointerCapture(e.Pointer); e.Handled = true; } private void DragTo(Point end) { if (start is not { } origin) return; var scaleX = surface.ActualWidth > 0 ? bounds.Width / surface.ActualWidth : surface.XamlRoot?.RasterizationScale ?? 1; var scaleY = surface.ActualHeight > 0 ? bounds.Height / surface.ActualHeight : surface.XamlRoot?.RasterizationScale ?? 1; // WinUI pointer coordinates use floats. Remove their subpixel rounding // noise before applying inclusive physical-pixel bounds. var originX = Math.Round(origin.X * scaleX, 4); var originY = Math.Round(origin.Y * scaleY, 4); var endX = Math.Round(end.X * scaleX, 4); var endY = Math.Round(end.Y * scaleY, 4); var region = pointMode ? new ScreenRegion(bounds.X + (int)Math.Clamp(Math.Floor(endX), 0, bounds.Width - 1), bounds.Y + (int)Math.Clamp(Math.Floor(endY), 0, bounds.Height - 1), 1, 1) : ScreenRegion.FromDrag(originX, originY, endX, endY, bounds); current = pointMode || region.Width >= 2 && region.Height >= 2 ? region : null; confirm.IsEnabled = current is not null; UpdateVisual(); } private void UpdateVisual() { var scale = surface.XamlRoot?.RasterizationScale ?? 1; var width = surface.ActualWidth > 0 ? surface.ActualWidth : bounds.Width / scale; var height = surface.ActualHeight > 0 ? surface.ActualHeight : bounds.Height / scale; var scaleX = bounds.Width / width; var scaleY = bounds.Height / height; var x = current is { } r ? (r.X - bounds.X) / scaleX : 0; var y = current is { } s ? (s.Y - bounds.Y) / scaleY : 0; var w = current?.Width / scaleX ?? 0; var h = current?.Height / scaleY ?? 0; Place(shade[0], 0, 0, width, y); Place(shade[1], 0, y + h, width, height - y - h); Place(shade[2], 0, y, x, h); Place(shade[3], x + w, y, width - x - w, h); Place(selection, x, y, w, h); label.Text = current is { } region ? $"X {region.X} · Y {region.Y}" + (pointMode ? "\nEnter 确认 · Esc 取消 · 点击重新选择" : $" · {region.Width} × {region.Height} 像素\nEnter 确认 · Esc 取消 · 可重新拖动框选") : pointMode ? "点击选择屏幕坐标 · Enter 确认 · Esc 取消" : templateMode ? "拖动框选目标模板 · Enter 确认 · Esc 取消" : "拖动框选识别区域 · Enter 确认 · Esc 取消"; var instructionWidth = Math.Min(500, Math.Max(220, width - 32)); instructions.Width = instructionWidth; Canvas.SetLeft(instructions, Math.Max(8, (width - instructionWidth) / 2)); Canvas.SetTop(instructions, Math.Max(8, height - (instructions.ActualHeight > 0 ? instructions.ActualHeight : 118) - 20)); } private static void Place(FrameworkElement element, double x, double y, double width, double height) { Canvas.SetLeft(element, x); Canvas.SetTop(element, y); element.Width = Math.Max(0, width); element.Height = Math.Max(0, height); } private void Complete(ScreenRegion? result) { if (completed.TrySetResult(result)) window.Close(); } private void PositionClient(RectInt32 rectangle) { window.AppWindow.MoveAndResize(rectangle); // Even a borderless OverlappedPresenter can retain invisible non-client // insets. The screenshot and pointer must share exactly the same pixels. for (var i = 0; i < 2; i++) { window.AppWindow.ResizeClient(new SizeInt32(rectangle.Width, rectangle.Height)); var origin = new NativePoint(); ClientToScreen(WinRT.Interop.WindowNative.GetWindowHandle(window), ref origin); var position = window.AppWindow.Position; window.AppWindow.Move(new PointInt32(position.X + rectangle.X - origin.X, position.Y + rectangle.Y - origin.Y)); } } [StructLayout(LayoutKind.Sequential)] private struct NativePoint { public int X; public int Y; } [DllImport("user32.dll")] private static extern bool ClientToScreen(nint window, ref NativePoint point); [DllImport("user32.dll")] private static extern bool GetCursorPos(out NativePoint point); [DllImport("user32.dll")] private static extern short GetAsyncKeyState(int key); [DllImport("user32.dll")] private static extern nint GetForegroundWindow(); private async Task LoadAsync(System.Drawing.Bitmap bitmap, CancellationToken ct = default) { using var data = new MemoryStream(); bitmap.Save(data, System.Drawing.Imaging.ImageFormat.Png); data.Position = 0; var source = new BitmapImage(); await source.SetSourceAsync(data.AsRandomAccessStream()); ct.ThrowIfCancellationRequested(); var image = new Image { Source = source, Stretch = Stretch.Fill, IsHitTestVisible = false }; surface.Children.Insert(0, image); void SizeImage() { var scale = surface.XamlRoot?.RasterizationScale ?? 1; image.Width = surface.ActualWidth > 0 ? surface.ActualWidth : bounds.Width / scale; image.Height = surface.ActualHeight > 0 ? surface.ActualHeight : bounds.Height / scale; } surface.SizeChanged += (_, _) => SizeImage(); SizeImage(); window.Activate(); surface.Focus(FocusState.Programmatic); UpdateVisual(); } public static async Task PickAsync(bool hideWorkflow, CancellationToken ct, bool pointMode = false) => (await PickDesktopAsync(hideWorkflow, ct, pointMode, false))?.Region; public static async Task PickTemplateAsync(CancellationToken ct) => (await PickDesktopAsync(true, ct, false, true))?.Template; private sealed record DesktopSelection(ScreenRegion Region, TemplateImageData? Template); private static async Task PickDesktopAsync(bool hideWorkflow, CancellationToken ct, bool pointMode, bool captureTemplate) { ct.ThrowIfCancellationRequested(); var restore = hideWorkflow && App.MainWindow.AppWindow.IsVisible; ScreenRegionPicker? picker = null; try { if (restore) { App.MainWindow.AppWindow.Hide(); await Task.Delay(220, ct); } using var screenshot = await Task.Run(() => ScreenCapture.Capture(), ct); ct.ThrowIfCancellationRequested(); picker = new(screenshot.Region, pointMode, captureTemplate); using var registration = ct.Register(() => picker.window.DispatcherQueue.TryEnqueue(() => picker.Complete(null))); await picker.LoadAsync(screenshot.Bitmap, ct); var result = await picker.completed.Task; ct.ThrowIfCancellationRequested(); if (result is not { } region) return null; // Crop the frozen original, never the shaded overlay or a later frame. var template = captureTemplate ? await Task.Run(() => TemplateImage.Crop(screenshot, region), ct) : null; return new(region, template); } finally { picker?.Complete(null); if (restore) { App.MainWindow.AppWindow.Show(); App.MainWindow.Activate(); } } } public static async Task PickImageAsync(string path, CancellationToken ct) { ct.ThrowIfCancellationRequested(); using var image = await Task.Run(() => ScreenCapture.Load(path), ct); var picker = new ScreenRegionPicker(image.Region); try { var work = DisplayArea.GetFromWindowId(App.MainWindow.AppWindow.Id, DisplayAreaFallback.Primary).WorkArea; var factor = Math.Min(1, Math.Min(work.Width * .85 / image.Region.Width, work.Height * .85 / image.Region.Height)); var width = Math.Max(400, (int)(image.Region.Width * factor)); var height = Math.Max(300, (int)(image.Region.Height * factor)); picker.PositionClient(new RectInt32(work.X + (work.Width - width) / 2, work.Y + (work.Height - height) / 2, width, height)); using var registration = ct.Register(() => picker.window.DispatcherQueue.TryEnqueue(() => picker.Complete(null))); await picker.LoadAsync(image.Bitmap, ct); var result = await picker.completed.Task; ct.ThrowIfCancellationRequested(); return result; } finally { picker.Complete(null); if (App.MainWindow.AppWindow.IsVisible) App.MainWindow.Activate(); } } // Use a fixture instead of capturing the user's desktop during automated UI verification. internal static async Task VerifyAsync(string screenshotPath) { using var bitmap = new System.Drawing.Bitmap(900, 600); using (var graphics = System.Drawing.Graphics.FromImage(bitmap)) { graphics.Clear(System.Drawing.Color.FromArgb(238, 242, 246)); using var font = new System.Drawing.Font("Microsoft YaHei UI", 26); graphics.DrawString("订单编号 XFE 12345\n待处理订单 8", font, System.Drawing.Brushes.Black, 90, 120); } var picker = new ScreenRegionPicker(new ScreenRegion(-900, 0, 900, 600), templateMode: true); var trace = new List(); void TracePointer(string name, PointerRoutedEventArgs e) { var point = e.GetCurrentPoint(picker.surface); trace.Add($"{name}: {point.Position}, left={point.Properties.IsLeftButtonPressed}, physicalLeft={(GetAsyncKeyState(1) & 0x8000) != 0}, timestamp={point.Timestamp}, source={e.OriginalSource?.GetType().Name}, region={picker.current}, start={picker.start}"); } picker.surface.PointerPressed += (_, e) => TracePointer("pressed", e); picker.surface.PointerMoved += (_, e) => TracePointer("moved", e); picker.surface.PointerReleased += (_, e) => TracePointer("released", e); picker.surface.PointerCaptureLost += (_, e) => TracePointer("capture-lost", e); try { picker.PositionClient(new RectInt32(80, 80, 900, 600)); await picker.LoadAsync(bitmap); await Task.Delay(160); var scale = picker.surface.XamlRoot.RasterizationScale; var handle = WinRT.Interop.WindowNative.GetWindowHandle(picker.window); Services.UiSmokeTest.SetForegroundWindow(handle); await Task.Delay(100); if (Services.UiSmokeTest.GetForegroundWindow() != handle) throw new InvalidOperationException("框选测试窗口未取得焦点,已停止鼠标输入"); var origin = new Services.UiSmokeTest.ScreenPoint(); Services.UiSmokeTest.ClientToScreen(handle, ref origin); trace.Add($"origin={origin.X},{origin.Y}, client={picker.window.AppWindow.ClientSize}, surface={picker.surface.ActualWidth},{picker.surface.ActualHeight}, scale={scale}"); try { Services.UiSmokeTest.MouseButtonAt(origin.X + 60, origin.Y + 80, true); await Task.Delay(80); for (var i = 0; i < 8; i++) { if (Services.UiSmokeTest.GetForegroundWindow() != handle) throw new InvalidOperationException("框选窗口失去焦点,已停止鼠标输入"); Services.UiSmokeTest.MouseMoveAt(origin.X + 60 + 80 * (i + 1), origin.Y + 80 + 30 * (i + 1)); await Task.Delay(35); } // Let the final native move reach WinUI before releasing the button. Services.UiSmokeTest.MouseMoveAt(origin.X + 700, origin.Y + 320); await Task.Delay(160); GetCursorPos(out var cursor); trace.Add($"final cursor={cursor.X},{cursor.Y}"); if (Services.UiSmokeTest.GetForegroundWindow() != handle) throw new InvalidOperationException("框选窗口失去焦点,已停止鼠标输入"); Services.UiSmokeTest.MouseButtonAt(origin.X + 700, origin.Y + 320, false); } finally { FlaUI.Core.Input.Mouse.Up(FlaUI.Core.Input.MouseButton.Left); } await Task.Delay(100); if (picker.current is not { } picked || Math.Abs(picked.Width - 640) > 2 || Math.Abs(picked.Height - 240) > 2 || Math.Abs(picked.X + 840) > 2 || Math.Abs(picked.Y - 80) > 2) throw new InvalidOperationException("鼠标框选或物理坐标换算错误:" + picker.current); using (var capture = ScreenCapture.Capture(new(origin.X + 60, origin.Y + 80, 640, 240))) { capture.Bitmap.Save(System.IO.Path.Combine(System.IO.Path.GetDirectoryName(screenshotPath)!, "region-capture-fixture.png"), System.Drawing.Imaging.ImageFormat.Png); using var recognizer = new OcrRecognizer(); var recognized = await Task.Run(() => recognizer.Recognize(capture, new() { ["scale"] = 1 }, default)); if (!recognized.String("text").Contains("12345", StringComparison.Ordinal)) throw new InvalidOperationException("物理屏幕区域 OCR 未识别出测试文本:" + recognized.String("text")); } var render = new RenderTargetBitmap(); await render.RenderAsync(picker.surface); var pixels = await render.GetPixelsAsync(); using var file = File.Create(screenshotPath); var encoder = await Windows.Graphics.Imaging.BitmapEncoder.CreateAsync(Windows.Graphics.Imaging.BitmapEncoder.PngEncoderId, file.AsRandomAccessStream()); encoder.SetPixelData(Windows.Graphics.Imaging.BitmapPixelFormat.Bgra8, Windows.Graphics.Imaging.BitmapAlphaMode.Premultiplied, (uint)render.PixelWidth, (uint)render.PixelHeight, 96, 96, pixels.ToArray()); await encoder.FlushAsync(); using (var frozen = new ScreenFrame((System.Drawing.Bitmap)bitmap.Clone(), picker.bounds, "screen")) { var template = TemplateImage.Crop(frozen, picked); using var restored = TemplateImage.Load(template.Value); for (var row = 0; row < restored.Bitmap.Height; row++) for (var col = 0; col < restored.Bitmap.Width; col++) if (restored.Bitmap.GetPixel(col, row).ToArgb() != bitmap.GetPixel(picked.X - picker.bounds.X + col, picked.Y - picker.bounds.Y + row).ToArgb()) throw new InvalidOperationException("框选模板混入遮罩或改变了原始像素"); restored.Bitmap.Save(System.IO.Path.Combine(System.IO.Path.GetDirectoryName(screenshotPath)!, "selected-screen-template.png"), System.Drawing.Imaging.ImageFormat.Png); } picker.Complete(picker.current); if (await picker.completed.Task is null) throw new InvalidOperationException("确认没有返回区域"); } finally { File.WriteAllLines(screenshotPath + ".trace.txt", trace); picker.Complete(null); } var cancelled = new ScreenRegionPicker(new ScreenRegion(80, 80, 900, 600), true); try { await cancelled.LoadAsync(bitmap); await Task.Delay(100); cancelled.start = new Point(0, 0); cancelled.DragTo(new Point(100, 80)); if (cancelled.current is not { Width: 1, Height: 1 }) throw new InvalidOperationException("坐标拾取模式未返回一个物理像素"); cancelled.Complete(null); if (await cancelled.completed.Task is not null) throw new InvalidOperationException("取消框选保留了新坐标"); } finally { cancelled.Complete(null); App.MainWindow.Activate(); } } }