namespace OcrDaemon; using System.Drawing; using System.Drawing.Imaging; using System.Runtime.InteropServices; static class ScreenCapture { [DllImport("user32.dll")] private static extern bool SetProcessDPIAware(); [DllImport("user32.dll")] private static extern int GetSystemMetrics(int nIndex); public static void InitDpiAwareness() => SetProcessDPIAware(); /// /// Capture from screen, or load from file if specified. /// When file is set, loads the image and crops to region. /// public static Bitmap CaptureOrLoad(string? file, RegionRect? region) { if (!string.IsNullOrEmpty(file)) { var fullBmp = new Bitmap(file); if (region != null) { int cx = Math.Max(0, region.X); int cy = Math.Max(0, region.Y); int cw = Math.Min(region.Width, fullBmp.Width - cx); int ch = Math.Min(region.Height, fullBmp.Height - cy); var cropped = fullBmp.Clone(new Rectangle(cx, cy, cw, ch), PixelFormat.Format32bppArgb); fullBmp.Dispose(); return cropped; } return fullBmp; } return CaptureScreen(region); } public static Bitmap CaptureScreen(RegionRect? region) { int x, y, w, h; if (region != null) { x = region.X; y = region.Y; w = region.Width; h = region.Height; } else { // Primary monitor only (0,0 origin, SM_CXSCREEN / SM_CYSCREEN) x = 0; y = 0; w = GetSystemMetrics(0); // SM_CXSCREEN h = GetSystemMetrics(1); // SM_CYSCREEN } var bitmap = new Bitmap(w, h, PixelFormat.Format32bppArgb); using var g = Graphics.FromImage(bitmap); g.CopyFromScreen(x, y, 0, 0, new System.Drawing.Size(w, h), CopyPixelOperation.SourceCopy); return bitmap; } }