// 区域截图 - 绿色工具箱 // 单文件零依赖,C# 5.0 语法(net48 自带 csc 可编译) // 功能:全屏遮罩拖框选区 → 保存 PNG/JPG 或复制到剪贴板;支持延迟截图(把窗口收起来的时间) // 边界:只截主屏所在虚拟屏;多显示器按虚拟屏整体截 using System; using System.Collections.Generic; using System.Drawing; using System.Drawing.Drawing2D; using System.Drawing.Imaging; using System.IO; using System.Text; using System.Windows.Forms; namespace GreenToolbox { public static class ShotOps { /* 拖拽方向不限:起点在右下也能框出正确的矩形 */ public static Rectangle Normalize(Point p1, Point p2) { return new Rectangle( Math.Min(p1.X, p2.X), Math.Min(p1.Y, p2.Y), Math.Abs(p1.X - p2.X), Math.Abs(p1.Y - p2.Y)); } /* 最小选区:小于 4×4 的框视为误触,取消 */ public static bool IsMeaningful(Rectangle r) { return r.Width >= 4 && r.Height >= 4; } public static Image CaptureScreen() { Rectangle bounds = SystemInformation.VirtualScreen; Bitmap bmp = new Bitmap(bounds.Width, bounds.Height, PixelFormat.Format32bppArgb); using (Graphics g = Graphics.FromImage(bmp)) { g.CopyFromScreen(bounds.X, bounds.Y, 0, 0, bounds.Size, CopyPixelOperation.SourceCopy); } return bmp; } /* 从整屏图里按屏幕坐标裁出选区(坐标以虚拟屏左上为原点偏移) */ public static Bitmap Crop(Image screen, Rectangle screenRect) { Rectangle vs = SystemInformation.VirtualScreen; Rectangle local = new Rectangle(screenRect.X - vs.X, screenRect.Y - vs.Y, screenRect.Width, screenRect.Height); local.Intersect(new Rectangle(0, 0, screen.Width, screen.Height)); Bitmap outBmp = new Bitmap(local.Width, local.Height, PixelFormat.Format32bppArgb); using (Graphics g = Graphics.FromImage(outBmp)) { g.DrawImage(screen, new Rectangle(0, 0, local.Width, local.Height), local, GraphicsUnit.Pixel); } return outBmp; } /* quality 只对 JPG 生效(1-100);返回写出字节数,失败抛异常 */ public static long Save(Image img, string file, int quality) { ImageFormat fmt = ImageFormat.Png; if (string.Equals(Path.GetExtension(file), ".jpg", StringComparison.OrdinalIgnoreCase) || string.Equals(Path.GetExtension(file), ".jpeg", StringComparison.OrdinalIgnoreCase)) fmt = ImageFormat.Jpeg; EncoderParameters ep = null; try { if (fmt == ImageFormat.Jpeg) { ImageCodecInfo jpg = FindCodec("image/jpeg"); ep = new EncoderParameters(1); ep.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, (long)Math.Max(1, Math.Min(100, quality))); img.Save(file, jpg, ep); } else { img.Save(file, fmt); } } finally { if (ep != null) ep.Dispose(); } return new FileInfo(file).Length; } public static ImageCodecInfo FindCodec(string mime) { ImageCodecInfo[] all = ImageCodecInfo.GetImageEncoders(); foreach (ImageCodecInfo c in all) { if (c.MimeType == mime) return c; } throw new IOException("找不到 " + mime + " 编码器"); } /* 文件名:截图_20260119_010203.png,重名自动 (2) */ public static string NextName(string dir, string ext) { string name = "截图_" + DateTime.Now.ToString("yyyyMMdd_HHmmss"); string p = Path.Combine(dir, name + ext); int k = 2; while (File.Exists(p)) { p = Path.Combine(dir, name + " (" + k + ")" + ext); k++; } return p; } } public class ShotOverlay : Form { private Image screen; private Point start; private Point cur; private bool dragging; public Rectangle Selected = Rectangle.Empty; public bool Cancelled = true; public ShotOverlay(Image fullScreen) { screen = fullScreen; this.FormBorderStyle = FormBorderStyle.None; this.Bounds = SystemInformation.VirtualScreen; this.StartPosition = FormStartPosition.Manual; this.TopMost = true; this.ShowInTaskbar = false; this.Cursor = Cursors.Cross; this.KeyPreview = true; this.DoubleBuffered = true; this.MouseDown += new MouseEventHandler(OnDown); this.MouseMove += new MouseEventHandler(OnMove); this.MouseUp += new MouseEventHandler(OnUp); this.KeyDown += new KeyEventHandler(OnKey); this.Paint += new PaintEventHandler(OnPaint); } private void OnDown(object sender, MouseEventArgs e) { if (e.Button != MouseButtons.Left) return; dragging = true; start = e.Location; cur = e.Location; } private void OnMove(object sender, MouseEventArgs e) { if (!dragging) return; cur = e.Location; this.Invalidate(); } private void OnUp(object sender, MouseEventArgs e) { if (!dragging) return; dragging = false; Selected = ShotOps.Normalize(start, e.Location); if (ShotOps.IsMeaningful(Selected)) { Cancelled = false; this.Close(); } else { this.Invalidate(); // 误触:清掉框继续选 } } private void OnKey(object sender, KeyEventArgs e) { if (e.KeyCode == Keys.Escape) this.Close(); } private void OnPaint(object sender, PaintEventArgs e) { Graphics g = e.Graphics; // 半透明黑遮罩:先整屏罩一层,再把选区抠亮 using (SolidBrush dim = new SolidBrush(Color.FromArgb(110, 0, 0, 0))) { g.FillRectangle(dim, this.ClientRectangle); } Rectangle r = dragging ? ShotOps.Normalize(start, cur) : Rectangle.Empty; if (r.Width > 0 && r.Height > 0) { g.DrawImage(screen, r, new Rectangle(r.X + this.Left - SystemInformation.VirtualScreen.X, r.Y + this.Top - SystemInformation.VirtualScreen.Y, r.Width, r.Height), GraphicsUnit.Pixel); using (Pen pen = new Pen(Color.FromArgb(0, 145, 88), 2f)) { g.DrawRectangle(pen, r); } string tip = r.Width + " × " + r.Height; using (Font f = new Font("Microsoft YaHei UI", 9f)) using (SolidBrush bg = new SolidBrush(Color.FromArgb(200, 0, 145, 88))) using (SolidBrush fg = new SolidBrush(Color.White)) { Size sz = TextRenderer.MeasureText(tip, f); Rectangle tipBox = new Rectangle(r.X, Math.Max(0, r.Y - sz.Height - 6), sz.Width + 12, sz.Height + 4); g.FillRectangle(bg, tipBox); g.DrawString(tip, f, fg, tipBox.X + 6, tipBox.Y + 2); } } else { using (Font f = new Font("Microsoft YaHei UI", 12f)) using (SolidBrush fg = new SolidBrush(Color.White)) { string tip = "拖拽框选截图区域,Esc 取消"; Size sz = TextRenderer.MeasureText(tip, f); g.DrawString(tip, f, fg, (this.Width - sz.Width) / 2, (this.Height - sz.Height) / 2); } } } protected override void Dispose(bool disposing) { if (disposing && screen != null) { screen.Dispose(); screen = null; } base.Dispose(disposing); } } public partial class ScreenshotForm : Form { private ComboBox cmbDelay; private ComboBox cmbFormat; private CheckBox chkCopy; private CheckBox chkHideCursorTip; private Button btnShot; private Label lblStatus; private System.Windows.Forms.Timer timer; private int ticksLeft; internal ScreenshotSelfTest.HookForTest hook; // 自测钩子(正常运行时为 null) public ScreenshotForm() { InitUi(); } private void InitUi() { this.Text = "区域截图 - 绿色工具箱"; this.Font = new Font("Microsoft YaHei UI", 9.5f); this.BackColor = Color.White; this.ForeColor = Color.FromArgb(34, 40, 36); this.ClientSize = new Size(560, 300); this.MinimumSize = new Size(560, 300); int x = 24, y = 18; Label lblTitle = new Label(); lblTitle.Text = "拖框截屏,存成 PNG/JPG 或直接进剪贴板;截图保存在「图片\\截图」或自选目录"; lblTitle.Location = new Point(x, y); lblTitle.AutoSize = true; lblTitle.ForeColor = Color.FromArgb(120, 130, 124); this.Controls.Add(lblTitle); y += 40; btnShot = new Button(); btnShot.Text = "开始截图"; btnShot.Location = new Point(x, y); btnShot.Size = new Size(150, 40); btnShot.BackColor = Color.FromArgb(0, 145, 88); btnShot.ForeColor = Color.White; btnShot.FlatStyle = FlatStyle.Flat; btnShot.Click += new EventHandler(ShotClick); this.Controls.Add(btnShot); Label l1 = new Label(); l1.Text = "延迟"; l1.Location = new Point(x + 170, y + 10); l1.AutoSize = true; this.Controls.Add(l1); cmbDelay = new ComboBox(); cmbDelay.DropDownStyle = ComboBoxStyle.DropDownList; cmbDelay.Items.AddRange(new object[] { "不延迟", "3 秒", "5 秒" }); cmbDelay.SelectedIndex = 0; cmbDelay.Location = new Point(x + 212, y + 7); cmbDelay.Size = new Size(80, 26); this.Controls.Add(cmbDelay); Label l2 = new Label(); l2.Text = "格式"; l2.Location = new Point(x + 306, y + 10); l2.AutoSize = true; this.Controls.Add(l2); cmbFormat = new ComboBox(); cmbFormat.DropDownStyle = ComboBoxStyle.DropDownList; cmbFormat.Items.AddRange(new object[] { "PNG(无损)", "JPG(体积小)" }); cmbFormat.SelectedIndex = 0; cmbFormat.Location = new Point(x + 348, y + 7); cmbFormat.Size = new Size(130, 26); this.Controls.Add(cmbFormat); y += 62; chkCopy = new CheckBox(); chkCopy.Text = "截图后同时复制到剪贴板"; chkCopy.Location = new Point(x, y); chkCopy.AutoSize = true; this.Controls.Add(chkCopy); y += 34; Button btnFolder = new Button(); btnFolder.Text = "打开截图文件夹"; btnFolder.Location = new Point(x, y); btnFolder.Size = new Size(150, 32); btnFolder.Click += new EventHandler(FolderClick); this.Controls.Add(btnFolder); y += 56; lblStatus = new Label(); lblStatus.Text = "按「开始截图」后窗口会自动让位,拖出想要的区域即可;Esc 取消。"; lblStatus.Location = new Point(x, y); lblStatus.AutoSize = true; lblStatus.ForeColor = Color.FromArgb(120, 130, 124); this.Controls.Add(lblStatus); timer = new System.Windows.Forms.Timer(); timer.Interval = 1000; timer.Tick += new EventHandler(Tick); } private void FolderClick(object sender, EventArgs e) { string dir = ShotDir(); if (!Directory.Exists(dir)) Directory.CreateDirectory(dir); System.Diagnostics.Process.Start("explorer.exe", "\"" + dir + "\""); } internal static string ShotDir() { string pic = Environment.GetFolderPath(Environment.SpecialFolder.MyPictures); if (string.IsNullOrEmpty(pic) || !Directory.Exists(pic)) pic = Environment.GetFolderPath(Environment.SpecialFolder.Desktop); string dir = Path.Combine(pic, "截图"); return dir; } private void ShotClick(object sender, EventArgs e) { int sec = cmbDelay.SelectedIndex == 1 ? 3 : (cmbDelay.SelectedIndex == 2 ? 5 : 0); if (sec > 0) { ticksLeft = sec; lblStatus.Text = sec + " 秒后开始,请把要截的画面摆好…"; timer.Start(); } else { DoShot(); } } private void Tick(object sender, EventArgs e) { ticksLeft--; if (ticksLeft <= 0) { timer.Stop(); DoShot(); } else lblStatus.Text = ticksLeft + " 秒后开始…"; } private void DoShot() { if (hook != null) { hook.OnShot(this); // 自测:只截屏不弹遮罩 return; } this.WindowState = FormWindowState.Minimized; this.ShowInTaskbar = false; Application.DoEvents(); System.Threading.Thread.Sleep(250); // 等窗口真的退到任务栏外 Image screen = null; ShotOverlay overlay = null; try { screen = ShotOps.CaptureScreen(); overlay = new ShotOverlay(screen); overlay.ShowDialog(this); if (overlay.Cancelled || overlay.Selected.IsEmpty) { lblStatus.Text = "已取消。"; return; } Finish(screen, overlay.Selected); } finally { if (overlay != null) overlay.Dispose(); if (screen != null) screen.Dispose(); this.WindowState = FormWindowState.Normal; this.ShowInTaskbar = true; } } /* 自测入口:跳过遮罩窗,直接走「截屏 → 裁剪 hook.Region → 保存」。 */ internal void SimulateShotForTest() { if (hook == null) return; hook.OnShot(this); } private void Finish(Image screen, Rectangle sel) { using (Bitmap shot = ShotOps.Crop(screen, sel)) { bool jpg = cmbFormat.SelectedIndex == 1; string ext = jpg ? ".jpg" : ".png"; string dir = ShotDir(); if (!Directory.Exists(dir)) Directory.CreateDirectory(dir); string file = ShotOps.NextName(dir, ext); ShotOps.Save(shot, file, jpg ? 90 : 100); if (chkCopy.Checked) { try { Clipboard.SetImage(shot); } catch { } } lblStatus.ForeColor = Color.FromArgb(0, 145, 88); lblStatus.Text = "已保存:" + file + "(" + sel.Width + "×" + sel.Height + ")"; } } } // ───────────────────────── 自测 ───────────────────────── public static class ScreenshotSelfTest { /* 给自测的钩子:不弹遮罩窗,只验证「截屏 + 裁剪 + 保存」链路 */ public class HookForTest { public Rectangle Region; public string LastFile; public void OnShot(ScreenshotForm form) { using (Image screen = ShotOps.CaptureScreen()) using (Bitmap shot = ShotOps.Crop(screen, Region)) { string dir = ScreenshotForm.ShotDir(); if (!Directory.Exists(dir)) Directory.CreateDirectory(dir); string file = ShotOps.NextName(dir, ".png"); ShotOps.Save(shot, file, 100); LastFile = file; } } } static int _pass, _fail; static List _lines = new List(); static void Check(string name, object got, object want) { bool ok = string.Equals(got == null ? "" : got.ToString(), want == null ? "" : want.ToString()); if (ok) { _pass++; _lines.Add(" [ok] " + name); } else { _fail++; _lines.Add(" [!!] " + name + " got=" + got + " want=" + want); } } public static int Run(string dir) { _pass = 0; _fail = 0; _lines = new List(); _lines.Add("区域截图 自测 " + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")); string baseDir = string.IsNullOrEmpty(dir) ? Path.Combine(Path.GetTempPath(), "gt-shot-" + Guid.NewGuid().ToString("N").Substring(0, 8)) : dir; try { Directory.CreateDirectory(baseDir); // 几何:反方向拖拽要能归一 Rectangle r = ShotOps.Normalize(new Point(500, 400), new Point(100, 120)); Check("反向拖拽归一", r.X + "," + r.Y + "," + r.Width + "," + r.Height, "100,120,400,280"); Check("同点没意义", ShotOps.IsMeaningful(ShotOps.Normalize(new Point(7, 7), new Point(7, 7))), false); Check("2×3 太小算误触", ShotOps.IsMeaningful(new Rectangle(0, 0, 2, 3)), false); Check("正常选区有意义", ShotOps.IsMeaningful(new Rectangle(0, 0, 800, 600)), true); // 编码器存在(win7 以后都有) Check("JPG 编码器", ShotOps.FindCodec("image/jpeg").MimeType, "image/jpeg"); Check("PNG 编码器", ShotOps.FindCodec("image/png").MimeType, "image/png"); // 保存链路:合成 400×300 带渐变的图,PNG / JPG 各存一遍 using (Bitmap bmp = new Bitmap(400, 300, PixelFormat.Format32bppArgb)) { using (Graphics g = Graphics.FromImage(bmp)) { using (LinearGradientBrush br = new LinearGradientBrush( new Rectangle(0, 0, 400, 300), Color.FromArgb(0, 145, 88), Color.White, 45f)) { g.FillRectangle(br, 0, 0, 400, 300); } g.FillEllipse(Brushes.Orange, 150, 100, 100, 100); } string png = Path.Combine(baseDir, "shot1.png"); string jpg = Path.Combine(baseDir, "shot2.jpg"); long p1 = ShotOps.Save(bmp, png, 100); long p2 = ShotOps.Save(bmp, jpg, 90); Check("PNG 写出", File.Exists(png) && p1 > 0, true); Check("JPG 写出", File.Exists(jpg) && p2 > 0, true); // 读回来核对内容与尺寸 using (Image back = Image.FromFile(png)) Check("PNG 尺寸", back.Width + "x" + back.Height, "400x300"); using (Image back = Image.FromFile(jpg)) Check("JPG 尺寸", back.Width + "x" + back.Height, "400x300"); // 质量参数越界要被夹住(1-100) string jpg2 = Path.Combine(baseDir, "shot3.jpg"); ShotOps.Save(bmp, jpg2, 5000); // 不抛异常即通过 Check("质量越界不炸", File.Exists(jpg2), true); } // 文件名去重 string d2 = Path.Combine(baseDir, "names"); Directory.CreateDirectory(d2); string n1 = ShotOps.NextName(d2, ".png"); File.WriteAllText(n1, "x"); string n2 = ShotOps.NextName(d2, ".png"); Check("重名加 (2)", Path.GetFileName(n1) != Path.GetFileName(n2) && Path.GetFileName(n2).Contains("(2)"), true); // 真截屏 + 裁剪链路(无头环境有桌面会话,CopyFromScreen 可用) Rectangle vs = SystemInformation.VirtualScreen; Rectangle region = new Rectangle(vs.X + 10, vs.Y + 10, 320, 240); HookForTest hook = new HookForTest(); hook.Region = region; ScreenshotForm form = new ScreenshotForm(); form.hook = hook; form.SimulateShotForTest(); // 内部只走截屏+裁剪+保存 Check("截屏链路产出文件", hook.LastFile != null && File.Exists(hook.LastFile), true); if (hook.LastFile != null) { using (Image back = Image.FromFile(hook.LastFile)) Check("裁剪尺寸", back.Width + "x" + back.Height, "320x240"); File.Delete(hook.LastFile); } form.Dispose(); } catch (Exception ex) { _fail++; _lines.Add(" [!!] 自测中途异常:" + ex.GetType().Name + " " + ex.Message); } finally { try { Directory.Delete(baseDir, true); } catch { } } _lines.Add(""); _lines.Add(_fail == 0 ? "结果:共 " + (_pass + _fail) + " 项,全部通过 ✓" : "结果:共 " + (_pass + _fail) + " 项,通过 " + _pass + ",失败 " + _fail + " ✗"); string all = string.Join("\r\n", _lines.ToArray()); Console.WriteLine(all); try { File.WriteAllText(Path.Combine(Directory.GetCurrentDirectory(), "selftest-screenshot.txt"), all, new UTF8Encoding(true)); } catch { } return _fail == 0 ? 0 : 1; } } static class Program { [STAThread] static void Main(string[] args) { if (args != null && args.Length > 0 && args[0] == "--selftest") { Environment.Exit(ScreenshotSelfTest.Run(args.Length >= 2 ? args[1] : null)); } Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new ScreenshotForm()); } } }