using System; using System.IO; using System.Windows; using System.Windows.Media; using System.Windows.Media.Imaging; namespace ClassNotify.Client.Services { public static class SimpleVisualReceipt { public static byte[]? Capture(Window window) { try { if (window == null) { return null; } double actualWidth = window.ActualWidth; double actualHeight = window.ActualHeight; if (actualWidth <= 0 || actualHeight <= 0) { actualWidth = window.Width > 0 ? window.Width : 960; actualHeight = window.Height > 0 ? window.Height : 600; } // Downscale proportionally if wider than 800px to keep payload lightweight (< 50 KiB) double scale = actualWidth > 800 ? 800.0 / actualWidth : 1.0; int targetW = (int)Math.Max(1, Math.Round(actualWidth * scale)); int targetH = (int)Math.Max(1, Math.Round(actualHeight * scale)); // Pure WPF RenderTargetBitmap: renders visual tree directly in memory // 100% immune to session lock, RDP disconnects, or invalid GDI screen handles var rtb = new RenderTargetBitmap(targetW, targetH, 96.0 * scale, 96.0 * scale, PixelFormats.Pbgra32); rtb.Render(window); using var ms = new MemoryStream(); var encoder = new JpegBitmapEncoder { QualityLevel = 82 }; encoder.Frames.Add(BitmapFrame.Create(rtb)); encoder.Save(ms); byte[] result = ms.ToArray(); return result.Length > 0 ? result : null; } catch (Exception ex) { try { File.AppendAllText(@"C:\ProgramData\ClassNotify\logs\client.log", $"[{DateTime.UtcNow:yyyy-MM-dd HH:mm:ss.fff}] [VisualReceipt.Capture] Exception: {ex.Message}\r\n"); } catch { } return null; } } } }