public static void CaptureActiveWindow(string path, imageFormats format = imageFormats.png, byte qualityJpeg = 90) { Rect rect = new Rect(); GetWindowRect(GetForegroundWindow(), ref rect); Rectangle bounds = new Rectangle(rect.Left, rect.Top, rect.Right - rect.Left, rect.Bottom - rect.Top); Bitmap bmp = new Bitmap(bounds.Width, bounds.Height); using (Graphics graphics = Graphics.FromImage(bmp)) { graphics.CopyFromScreen(new Point(bounds.Left, bounds.Top), Point.Empty, bounds.Size); } saveToFile(ref bmp, path, format, qualityJpeg); }
public static void CaptureDesktop(string path, imageFormats format = imageFormats.png, byte qualityJpeg = 100) { int screenLeft = int.MaxValue; int screenTop = int.MaxValue; int screenRight = int.MinValue; int screenBottom = int.MinValue; int deviceIndex = 0; while (true) { NativeUtilities.DisplayDevice deviceData = new NativeUtilities.DisplayDevice { cb = Marshal.SizeOf(typeof(NativeUtilities.DisplayDevice)) }; if (NativeUtilities.EnumDisplayDevices(null, deviceIndex, ref deviceData, 0) != 0) { NativeUtilities.DEVMODE devMode = new NativeUtilities.DEVMODE(); if (NativeUtilities.EnumDisplaySettings(deviceData.DeviceName, NativeUtilities.ENUM_CURRENT_SETTINGS, ref devMode)) { screenLeft = Math.Min(screenLeft, devMode.dmPositionX); screenTop = Math.Min(screenTop, devMode.dmPositionY); screenRight = Math.Max(screenRight, devMode.dmPositionX + devMode.dmPelsWidth); screenBottom = Math.Max(screenBottom, devMode.dmPositionY + devMode.dmPelsHeight); } deviceIndex++; } else { break; } } Bitmap bmp = new Bitmap(screenRight - screenLeft, screenBottom - screenTop); using (Graphics g = Graphics.FromImage(bmp)) g.CopyFromScreen(screenLeft, screenTop, 0, 0, bmp.Size); saveToFile(ref bmp, path, format, qualityJpeg); }
private static void saveToFile(ref Bitmap bmp, string path, imageFormats format, byte qualityJpeg = 90) { switch (format) { case imageFormats.bmp: bmp.Save(path, ImageFormat.Bmp); break; case imageFormats.png: bmp.Save(path, ImageFormat.Png); break; case imageFormats.gif: bmp.Save(path, ImageFormat.Gif); break; case imageFormats.jpg: EncoderParameters encoderParameters = new EncoderParameters(1); encoderParameters.Param[0] = new EncoderParameter(Encoder.Quality, (Int64)qualityJpeg); bmp.Save(path, GetEncoder(ImageFormat.Jpeg), encoderParameters); break; } }