using System.IO; using System.Runtime.InteropServices; using System.Windows; using System.Windows.Interop; using System.Windows.Media; using System.Windows.Media.Imaging; using Windows.Graphics.Imaging; using Windows.Media.Ocr; using Windows.Storage.Streams; namespace XFEToolBox.QuickTools; public sealed record ScreenCapture(BitmapSource Image, int Left, int Top); public static class ScreenTools { public static ScreenCapture CaptureDesktop() { int x = GetSystemMetrics(76), y = GetSystemMetrics(77), width = GetSystemMetrics(78), height = GetSystemMetrics(79); if (width <= 0 || height <= 0 || (long)width * height > 64_000_000) throw new InvalidOperationException("桌面尺寸无效或超过 6400 万像素。"); using var bitmap = new System.Drawing.Bitmap(width, height, System.Drawing.Imaging.PixelFormat.Format32bppArgb); using (var graphics = System.Drawing.Graphics.FromImage(bitmap)) graphics.CopyFromScreen(x, y, 0, 0, new System.Drawing.Size(width, height), System.Drawing.CopyPixelOperation.SourceCopy); nint handle = bitmap.GetHbitmap(); try { var image = Imaging.CreateBitmapSourceFromHBitmap(handle, 0, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions()); image.Freeze(); return new(image, x, y); } finally { DeleteObject(handle); } } public static Int32Rect PixelBounds(Rect rectangle, Size viewSize, BitmapSource image) { if (viewSize.Width <= 0 || viewSize.Height <= 0) throw new ArgumentException("尚未完成布局。"); int x = Math.Clamp((int)Math.Floor(rectangle.X * image.PixelWidth / viewSize.Width), 0, image.PixelWidth - 1), y = Math.Clamp((int)Math.Floor(rectangle.Y * image.PixelHeight / viewSize.Height), 0, image.PixelHeight - 1); int right = Math.Clamp((int)Math.Ceiling(rectangle.Right * image.PixelWidth / viewSize.Width), x + 1, image.PixelWidth), bottom = Math.Clamp((int)Math.Ceiling(rectangle.Bottom * image.PixelHeight / viewSize.Height), y + 1, image.PixelHeight); return new(x, y, right - x, bottom - y); } public static BitmapSource Crop(BitmapSource image, Int32Rect rectangle) { var crop = new CroppedBitmap(image, rectangle); crop.Freeze(); return crop; } public static string ColorAt(BitmapSource image, int x, int y) { var formatted = new FormatConvertedBitmap(image, PixelFormats.Bgra32, null, 0); byte[] pixel = new byte[4]; formatted.CopyPixels(new Int32Rect(Math.Clamp(x, 0, image.PixelWidth - 1), Math.Clamp(y, 0, image.PixelHeight - 1), 1, 1), pixel, 4, 0); return $"#{pixel[2]:X2}{pixel[1]:X2}{pixel[0]:X2} · RGB({pixel[2]}, {pixel[1]}, {pixel[0]})"; } public static string[] OcrLanguages() => OcrEngine.AvailableRecognizerLanguages.Select(l => l.LanguageTag).ToArray(); public static async Task Recognize(BitmapSource image, string? language = null, CancellationToken token = default) { var engine = language is null ? OcrEngine.TryCreateFromUserProfileLanguages() : OcrEngine.TryCreateFromLanguage(new Windows.Globalization.Language(language)); engine ??= OcrEngine.AvailableRecognizerLanguages.Select(OcrEngine.TryCreateFromLanguage).FirstOrDefault(e => e is not null); if (engine is null) throw new InvalidOperationException("未安装 Windows OCR 语言包。请在 Windows 设置中添加语言及 OCR 功能后重试。"); double scale = Math.Min(1, (double)OcrEngine.MaxImageDimension / Math.Max(image.PixelWidth, image.PixelHeight)); if (scale < 1) image = new TransformedBitmap(image, new ScaleTransform(scale, scale)); var encoder = new PngBitmapEncoder(); encoder.Frames.Add(System.Windows.Media.Imaging.BitmapFrame.Create(image)); using var bytes = new MemoryStream(); encoder.Save(bytes); using var stream = new InMemoryRandomAccessStream(); using (var writer = new DataWriter(stream)) { writer.WriteBytes(bytes.ToArray()); await writer.StoreAsync().AsTask(token); writer.DetachStream(); } stream.Seek(0); var decoder = await Windows.Graphics.Imaging.BitmapDecoder.CreateAsync(stream).AsTask(token); using var bitmap = await decoder.GetSoftwareBitmapAsync(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Premultiplied).AsTask(token); var result = await engine.RecognizeAsync(bitmap).AsTask(token); return string.Join(Environment.NewLine, result.Lines.Select(l => l.Text)); } [DllImport("user32.dll")] private static extern int GetSystemMetrics(int n); [DllImport("gdi32.dll")] private static extern bool DeleteObject(nint handle); }