using System.Drawing; using System.Drawing.Imaging; using System.Runtime.InteropServices; using System.Text; namespace RynthCore.StatusAgent; /// /// Captures an AC client window's on-screen rectangle as a JPEG. Out-of-process (GDI BitBlt of the /// composited desktop), so the game/engine is never touched. Only works on a window that's actually /// rendering — a minimized client has no frame. Captures whatever is on top of the window too, so /// docked overlays show; undocked panels (separate windows elsewhere) don't. /// internal static class ScreenCapture { public enum Result { Ok, NotFound, Minimized, Error } private static bool _dpiSet; private static void EnsureDpiAware() { if (_dpiSet) return; _dpiSet = true; try { if (SetProcessDpiAwarenessContext(DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2)) return; } catch { } try { SetProcessDPIAware(); } catch { } } /// If >0 and wider, downscale to this width (preserve aspect) before encoding. /// Uses PrintWindow(PW_RENDERFULLCONTENT) so it captures the window's OWN content regardless of what's /// on top of it (a foreground app over the client no longer leaks into the frame). Cropped to the /// client area (no title bar). Separate overlay windows (Avalonia panels) are NOT included — by design. public static Result TryCaptureJpeg(int pid, int quality, int maxWidth, out byte[] jpeg) { jpeg = Array.Empty(); EnsureDpiAware(); if (!TryFindWindow(pid, out IntPtr hwnd, out bool minimized)) return minimized ? Result.Minimized : Result.NotFound; try { if (!GetWindowRect(hwnd, out RECT wr)) return Result.Error; int ww = wr.Right - wr.Left, wh = wr.Bottom - wr.Top; if (ww < 8 || wh < 8) return Result.Error; using var full = new Bitmap(ww, wh, PixelFormat.Format24bppRgb); bool ok; using (var g = Graphics.FromImage(full)) { IntPtr hdc = g.GetHdc(); ok = PrintWindow(hwnd, hdc, PW_RENDERFULLCONTENT); g.ReleaseHdc(hdc); } if (!ok) return Result.Error; // Crop the title bar / borders away (client area only) for a clean view. Bitmap img = full; Rectangle crop = ClientCrop(hwnd, wr, ww, wh); if (crop.Width >= 8 && crop.Height >= 8 && (crop.Width < ww || crop.Height < wh)) img = full.Clone(crop, full.PixelFormat); try { if (maxWidth > 0 && img.Width > maxWidth) { int dw = maxWidth, dh = Math.Max(1, (int)Math.Round(img.Height * (maxWidth / (double)img.Width))); using var scaled = new Bitmap(dw, dh, PixelFormat.Format24bppRgb); using (var g = Graphics.FromImage(scaled)) { g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.Bilinear; g.PixelOffsetMode = System.Drawing.Drawing2D.PixelOffsetMode.Half; g.DrawImage(img, 0, 0, dw, dh); } jpeg = EncodeJpeg(scaled, quality); } else jpeg = EncodeJpeg(img, quality); } finally { if (!ReferenceEquals(img, full)) img.Dispose(); } return Result.Ok; } catch { return Result.Error; } } /// The client-area rectangle within the full-window bitmap (0,0 = window top-left). private static Rectangle ClientCrop(IntPtr hwnd, RECT wr, int ww, int wh) { try { if (GetClientRect(hwnd, out RECT cr)) { POINT origin = default; if (ClientToScreen(hwnd, ref origin)) { int ox = origin.X - wr.Left, oy = origin.Y - wr.Top; int cw = cr.Right - cr.Left, ch = cr.Bottom - cr.Top; if (ox >= 0 && oy >= 0 && cw > 0 && ch > 0 && ox + cw <= ww && oy + ch <= wh) return new Rectangle(ox, oy, cw, ch); } } } catch { } return new Rectangle(0, 0, ww, wh); } private static ImageCodecInfo? _jpegEncoder; private static byte[] EncodeJpeg(Bitmap bmp, int quality) { _jpegEncoder ??= Array.Find(ImageCodecInfo.GetImageEncoders(), c => c.FormatID == ImageFormat.Jpeg.Guid) ?? throw new InvalidOperationException("no jpeg encoder"); using var ep = new EncoderParameters(1); ep.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, (long)Math.Clamp(quality, 1, 100)); using var ms = new MemoryStream(); bmp.Save(ms, _jpegEncoder, ep); return ms.ToArray(); } /// True when the client's game window exists but is minimized (so capture would only get black). public static bool IsClientMinimized(int pid) { EnsureDpiAware(); TryFindWindow(pid, out _, out bool minimized); return minimized; } /// PostMessage a mouse click to the acclient window at normalized (u,v) of its CLIENT area — the exact /// area the stream captures. acclient reads clicks from window messages (verified in the decompile: /// Device::WndProc dispatches WM_LBUTTONDOWN/etc by lParam, never GetCursorPos), so this drives both the /// 2D UI and 3D-world hit-test WITHOUT moving the real cursor or stealing focus, even when the window is /// backgrounded/occluded — multibox-safe. Returns false if the window is missing or minimized. public enum ClickResult { Posted, NotFound, Minimized, NoClientArea, PostFailed } /// What one tap did: where it went in the client area (and how big that is), or why not. public readonly record struct ClickOutcome(ClickResult Result, int X, int Y, int Width, int Height) { public string Reason => Result switch { ClickResult.Posted => "posted", ClickResult.NotFound => "no game window for that pid", ClickResult.Minimized => "the game window is minimized", ClickResult.NoClientArea => "the game window has no client area", _ => "PostMessage failed", }; } // Give the game a frame between the move and the press, and between press and release: RynthCore // can throttle a background client (Background FPS, 5..60), and a move + press + release that all land // inside one frame can read to AC as a press at the old cursor spot, or as nothing at all. private const int MoveSettleMs = 60; private const int PressHoldMs = 90; public static ClickOutcome TryClick(int pid, double u, double v, string? button) { EnsureDpiAware(); if (!TryFindWindow(pid, out IntPtr hwnd, out bool minimized) || hwnd == IntPtr.Zero) return new ClickOutcome(minimized ? ClickResult.Minimized : ClickResult.NotFound, 0, 0, 0, 0); if (!GetClientRect(hwnd, out RECT cr)) return new ClickOutcome(ClickResult.NoClientArea, 0, 0, 0, 0); int cw = cr.Right - cr.Left, ch = cr.Bottom - cr.Top; if (cw < 2 || ch < 2) return new ClickOutcome(ClickResult.NoClientArea, 0, 0, cw, ch); var (x, y) = RemoteParity.ClickPoint(u, v, cw, ch); IntPtr lParam = RemoteParity.MouseLParam(x, y); bool right = string.Equals(button, "right", StringComparison.OrdinalIgnoreCase); IntPtr held = (IntPtr)(right ? MK_RBUTTON : MK_LBUTTON); try { if (!PostMessage(hwnd, WM_MOUSEMOVE, IntPtr.Zero, lParam)) return new ClickOutcome(ClickResult.PostFailed, x, y, cw, ch); System.Threading.Thread.Sleep(MoveSettleMs); PostMessage(hwnd, right ? WM_RBUTTONDOWN : WM_LBUTTONDOWN, held, lParam); System.Threading.Thread.Sleep(PressHoldMs); // down→up apart so AC registers a click, not a drag PostMessage(hwnd, right ? WM_RBUTTONUP : WM_LBUTTONUP, IntPtr.Zero, lParam); return new ClickOutcome(ClickResult.Posted, x, y, cw, ch); } catch { return new ClickOutcome(ClickResult.PostFailed, x, y, cw, ch); } } /// Pick the game window for this pid: the largest visible, non-minimized acclient-class window. The /// acclient (D3D9) window is the only one worth capturing — the process's other top-level windows are /// the separate Avalonia overlay panels (excluded by design). Crucially, if the acclient window is /// MINIMIZED we report minimized=true rather than falling back to a non-game window and capturing a /// black frame (the old bug). Falls back to the largest visible window only when the pid has no /// acclient-class window at all (defensive — keeps capture working if the class ever differs). private static bool TryFindWindow(int pid, out IntPtr best, out bool minimized) { IntPtr acWin = IntPtr.Zero; long acArea = 0; // best non-minimized acclient window IntPtr anyWin = IntPtr.Zero; long anyArea = 0; // best non-minimized window of any class (fallback) bool acMinimized = false; // an acclient window exists but is minimized var sb = new StringBuilder(64); EnumWindows((h, l) => { if (GetWindowThreadProcessId(h, out uint wpid) == 0 || wpid != (uint)pid) return true; if (!IsWindowVisible(h)) return true; sb.Clear(); GetClassName(h, sb, sb.Capacity); bool isAc = sb.ToString().IndexOf("acclient", StringComparison.OrdinalIgnoreCase) >= 0; if (IsIconic(h)) { if (isAc) acMinimized = true; return true; } if (!GetWindowRect(h, out RECT r)) return true; long area = (long)Math.Max(0, r.Right - r.Left) * Math.Max(0, r.Bottom - r.Top); if (area < 64) return true; if (isAc) { if (area > acArea) { acArea = area; acWin = h; } } else if (area > anyArea) { anyArea = area; anyWin = h; } return true; }, IntPtr.Zero); if (acWin != IntPtr.Zero) { best = acWin; minimized = false; return true; } // got the game window if (acMinimized) { best = IntPtr.Zero; minimized = true; return false; } // game window is minimized best = anyWin; minimized = false; return anyWin != IntPtr.Zero; // no acclient window at all } private static bool TryGetBounds(IntPtr hwnd, out int x, out int y, out int w, out int h) { x = y = w = h = 0; // DWM extended frame bounds = the visible rect (excludes the invisible resize border on Win10+). if (DwmGetWindowAttribute(hwnd, DWMWA_EXTENDED_FRAME_BOUNDS, out RECT r, Marshal.SizeOf()) != 0) { if (!GetWindowRect(hwnd, out r)) return false; } x = r.Left; y = r.Top; w = r.Right - r.Left; h = r.Bottom - r.Top; return w > 0 && h > 0; } // ── P/Invoke ──────────────────────────────────────────────────────────── [StructLayout(LayoutKind.Sequential)] private struct RECT { public int Left, Top, Right, Bottom; } [StructLayout(LayoutKind.Sequential)] private struct POINT { public int X, Y; } [DllImport("user32.dll")] private static extern bool PrintWindow(IntPtr hWnd, IntPtr hdcBlt, uint nFlags); private const uint PW_RENDERFULLCONTENT = 0x00000002; // capture D3D/GPU content (Win8.1+) [DllImport("user32.dll")] private static extern bool GetClientRect(IntPtr hWnd, out RECT r); [DllImport("user32.dll")] private static extern bool PostMessage(IntPtr hWnd, uint Msg, IntPtr wParam, IntPtr lParam); private const uint WM_MOUSEMOVE = 0x0200, WM_LBUTTONDOWN = 0x0201, WM_LBUTTONUP = 0x0202, WM_RBUTTONDOWN = 0x0204, WM_RBUTTONUP = 0x0205; private const int MK_LBUTTON = 0x0001, MK_RBUTTON = 0x0002; [DllImport("user32.dll")] private static extern bool ClientToScreen(IntPtr hWnd, ref POINT p); private delegate bool EnumWindowsProc(IntPtr hWnd, IntPtr lParam); [DllImport("user32.dll")] private static extern bool EnumWindows(EnumWindowsProc cb, IntPtr lParam); [DllImport("user32.dll")] private static extern uint GetWindowThreadProcessId(IntPtr hWnd, out uint pid); [DllImport("user32.dll")] private static extern bool IsWindowVisible(IntPtr hWnd); [DllImport("user32.dll")] private static extern bool IsIconic(IntPtr hWnd); [DllImport("user32.dll", CharSet = CharSet.Unicode)] private static extern int GetClassName(IntPtr hWnd, StringBuilder s, int max); [DllImport("user32.dll")] private static extern bool GetWindowRect(IntPtr hWnd, out RECT r); [DllImport("dwmapi.dll")] private static extern int DwmGetWindowAttribute(IntPtr hWnd, int attr, out RECT r, int size); private const int DWMWA_EXTENDED_FRAME_BOUNDS = 9; [DllImport("user32.dll")] private static extern bool SetProcessDPIAware(); [DllImport("user32.dll")] private static extern bool SetProcessDpiAwarenessContext(IntPtr ctx); private static readonly IntPtr DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2 = new(-4); }