// 截图贴图 - 绿色工具箱 // 单文件零依赖,C# 5.0 语法(net48 自带 csc 可编译) // 功能:截一块屏幕区域,直接「钉」在屏幕上悬浮显示(Snipaste 式贴图); // 贴图可拖动、滚轮缩放、Ctrl+滚轮调透明度、右键复制/保存/关闭,可同时贴多张。 // 边界:贴图是普通置顶窗口,在全屏游戏/部分 UWP 之上可能被盖住,属系统限制,如实说明。 using System; using System.Collections.Generic; using System.Drawing; using System.Drawing.Drawing2D; using System.Drawing.Imaging; using System.IO; using System.Runtime.InteropServices; using System.Text; using System.Windows.Forms; namespace GreenToolbox { public static class PinOps { /* 拖拽方向不限:起点在右下也能框出正确的矩形 */ 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 const double MinZoom = 0.2; public const double MaxZoom = 5.0; public const double ZoomStep = 1.1; // 滚轮一格放大/缩小 10% public static double ClampZoom(double z) { if (z < MinZoom) return MinZoom; if (z > MaxZoom) return MaxZoom; return z; } /* 滚轮一格后的新倍率;delta 是 MouseEventArgs.Delta(上滚为正) */ public static double StepZoom(double cur, int delta) { double z = cur; if (delta > 0) z = cur * ZoomStep; else if (delta < 0) z = cur / ZoomStep; return ClampZoom(z); } /* 光标锚缩放:缩放前后光标指着的画面点不动(不然一滚轮图就飞走) 几何:rel = cursor - loc;newRel = rel * newZoom/oldZoom;newLoc = cursor - newRel */ public static Point ZoomedLocation(Point cursor, Point oldLoc, double oldZoom, double newZoom) { double rx = (cursor.X - oldLoc.X) * newZoom / oldZoom; double ry = (cursor.Y - oldLoc.Y) * newZoom / oldZoom; return new Point( (int)Math.Round(cursor.X - rx), (int)Math.Round(cursor.Y - ry)); } /* 贴图窗口显示尺寸(原始像素 × 倍率,四舍五入,最小 1px) */ public static Size DisplaySize(int w, int h, double zoom) { return new Size( Math.Max(1, (int)Math.Round(w * zoom)), Math.Max(1, (int)Math.Round(h * zoom))); } /* 透明度档位(窗体 Opacity 0.15~1.0,越界夹回) */ public static double ClampOpacity(double o) { if (o < 0.15) return 0.15; if (o > 1.0) return 1.0; return o; } 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; } /* PNG 保存(贴图带清晰文字,默认只用 PNG 不做有损) */ public static long SavePng(Image img, string file) { img.Save(file, ImageFormat.Png); return new FileInfo(file).Length; } /* 文件名:贴图_20261022_121530.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; } internal static string PinDir() { string pic = Environment.GetFolderPath(Environment.SpecialFolder.MyPictures); if (string.IsNullOrEmpty(pic) || !Directory.Exists(pic)) pic = Environment.GetFolderPath(Environment.SpecialFolder.Desktop); return Path.Combine(pic, "截图"); } } /* 全屏遮罩拖框选区(与区域截图同款交互) */ public class PinOverlay : Form { private Image screen; private Point start; private Point cur; private bool dragging; public Rectangle Selected = Rectangle.Empty; public bool Cancelled = true; public PinOverlay(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 = PinOps.Normalize(start, e.Location); if (PinOps.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 ? PinOps.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); } } /* 贴图窗:无边框置顶悬浮,拖动 / 滚轮缩放 / Ctrl+滚轮透明度 / 右键菜单 */ public class PinForm : Form { private Bitmap shot; // 原始像素 private double zoom = 1.0; private double opacity = 1.0; private Point dragLast; private bool dragging; private bool headless; // 自测标志:不弹菜单、不碰剪贴板 public PinForm(Bitmap image, Rectangle screenRect, bool forTest) { shot = image; headless = forTest; this.FormBorderStyle = FormBorderStyle.None; this.StartPosition = FormStartPosition.Manual; this.TopMost = true; this.ShowInTaskbar = false; this.ShowIcon = false; this.KeyPreview = true; this.DoubleBuffered = true; this.Bounds = new Rectangle(screenRect.Location, PinOps.DisplaySize(shot.Width, shot.Height, zoom)); this.MouseDown += new MouseEventHandler(OnDown); this.MouseMove += new MouseEventHandler(OnMove); this.MouseUp += new MouseEventHandler(OnUp); this.MouseWheel += new MouseEventHandler(OnWheel); this.DoubleClick += new EventHandler(OnDbl); this.KeyDown += new KeyEventHandler(OnKey); this.Paint += new PaintEventHandler(OnPaint); BuildMenu(); } public double CurrentZoom { get { return zoom; } } public double CurrentOpacity { get { return opacity; } } public Bitmap ShotImage { get { return shot; } } /* 供自测直接驱动:不碰真实鼠标 */ internal void TestZoom(Point cursor, int delta) { ApplyZoom(cursor, PinOps.StepZoom(zoom, delta)); } internal void TestSetOpacity(double o) { opacity = PinOps.ClampOpacity(o); this.Opacity = opacity; } private void ApplyZoom(Point cursor, double newZoom) { if (Math.Abs(newZoom - zoom) < 0.0001) return; this.Location = PinOps.ZoomedLocation(cursor, this.Location, zoom, newZoom); zoom = newZoom; this.Size = PinOps.DisplaySize(shot.Width, shot.Height, zoom); this.Invalidate(); } private void OnDown(object sender, MouseEventArgs e) { if (e.Button != MouseButtons.Left) return; dragging = true; dragLast = Cursor.Position; } private void OnMove(object sender, MouseEventArgs e) { if (!dragging) return; Point now = Cursor.Position; this.Location = new Point(this.Left + now.X - dragLast.X, this.Top + now.Y - dragLast.Y); dragLast = now; } private void OnUp(object sender, MouseEventArgs e) { dragging = false; } private void OnWheel(object sender, MouseEventArgs e) { if ((Control.ModifierKeys & Keys.Control) != 0) { // Ctrl+滚轮:透明度,上滚更实、下滚更透 TestSetOpacity(opacity + (e.Delta > 0 ? 0.1 : -0.1)); } else { ApplyZoom(Cursor.Position, PinOps.StepZoom(zoom, e.Delta)); } } private void OnDbl(object sender, EventArgs e) { this.Close(); } 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; g.InterpolationMode = InterpolationMode.HighQualityBicubic; g.PixelOffsetMode = PixelOffsetMode.HighQuality; g.DrawImage(shot, new Rectangle(0, 0, this.Width, this.Height)); using (Pen pen = new Pen(Color.FromArgb(0, 145, 88), 1f)) { g.DrawRectangle(pen, 0, 0, this.Width - 1, this.Height - 1); } } private void BuildMenu() { ContextMenuStrip menu = new ContextMenuStrip(); menu.Items.Add("复制图片", null, new EventHandler(delegate { CopyShot(); })); menu.Items.Add("保存为 PNG(图片\\截图)", null, new EventHandler(delegate { SaveShot(); })); menu.Items.Add(new ToolStripSeparator()); ToolStripMenuItem mz = new ToolStripMenuItem("缩放"); mz.DropDownItems.Add("放大 10%", null, new EventHandler(delegate { ApplyZoom(Cursor.Position, PinOps.ClampZoom(zoom * PinOps.ZoomStep)); })); mz.DropDownItems.Add("缩小 10%", null, new EventHandler(delegate { ApplyZoom(Cursor.Position, PinOps.ClampZoom(zoom / PinOps.ZoomStep)); })); mz.DropDownItems.Add("恢复 100%", null, new EventHandler(delegate { ApplyZoom(Cursor.Position, 1.0); })); menu.Items.Add(mz); ToolStripMenuItem mo = new ToolStripMenuItem("透明度"); string[] labels = new string[] { "不透明", "85%", "70%", "55%", "40%", "25%" }; double[] vals = new double[] { 1.0, 0.85, 0.7, 0.55, 0.4, 0.25 }; for (int i = 0; i < labels.Length; i++) { double v = vals[i]; mo.DropDownItems.Add(labels[i], null, new EventHandler(delegate { TestSetOpacity(v); })); } menu.Items.Add(mo); menu.Items.Add(new ToolStripSeparator()); menu.Items.Add("关闭贴图(双击同效)", null, new EventHandler(delegate { this.Close(); })); this.ContextMenuStrip = menu; } private void CopyShot() { if (headless) return; try { Clipboard.SetImage(shot); } catch { } } private void SaveShot() { string dir = PinOps.PinDir(); if (!Directory.Exists(dir)) Directory.CreateDirectory(dir); string file = PinOps.NextName(dir, ".png"); PinOps.SavePng(shot, file); if (headless) return; try { NotifyTip("贴图已保存:" + file); } catch { } } internal void NotifyTip(string text) { NotifyIcon ni = new NotifyIcon(); ni.Icon = SystemIcons.Application; ni.Visible = true; ni.BalloonTipTitle = "截图贴图"; ni.BalloonTipText = text; ni.ShowBalloonTip(1500); System.Windows.Forms.Timer t = new System.Windows.Forms.Timer(); t.Interval = 2200; t.Tick += new EventHandler(delegate { ni.Visible = false; ni.Dispose(); t.Stop(); t.Dispose(); }); t.Start(); } protected override void Dispose(bool disposing) { if (disposing && shot != null) { shot.Dispose(); shot = null; } base.Dispose(disposing); } } public partial class SnapPinForm : Form { private Button btnPin; private Button btnCloseAll; private Button btnHide; private Label lblStatus; private Label lblCount; internal SnapPinSelfTest.HookForTest hook; // 自测钩子(正常运行时为 null) /* 全局热键:Ctrl+Alt+S 再贴一张(失败不致命,按钮仍在) */ private const int HOTKEY_PIN = 0x9001; private const uint MOD_CONTROL = 0x2, MOD_ALT = 0x1; private const int WM_HOTKEY = 0x0312; [DllImport("user32.dll")] private static extern bool RegisterHotKey(IntPtr h, int id, uint mod, uint vk); [DllImport("user32.dll")] private static extern bool UnregisterHotKey(IntPtr h, int id); public SnapPinForm() { 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(700, 330); int x = 24, y = 18; Label lblTitle = new Label(); lblTitle.Text = "截一块屏幕区域,直接「钉」在桌面上悬浮对照——抄代码、对着填单、看图做表不用来回切窗口"; lblTitle.Location = new Point(x, y); lblTitle.AutoSize = true; lblTitle.ForeColor = Color.FromArgb(120, 130, 124); this.Controls.Add(lblTitle); y += 42; btnPin = new Button(); btnPin.Text = "贴一张(Ctrl+Alt+S)"; btnPin.Location = new Point(x, y); btnPin.Size = new Size(190, 40); btnPin.BackColor = Color.FromArgb(0, 145, 88); btnPin.ForeColor = Color.White; btnPin.FlatStyle = FlatStyle.Flat; btnPin.Click += new EventHandler(PinClick); this.Controls.Add(btnPin); btnCloseAll = new Button(); btnCloseAll.Text = "关闭全部贴图"; btnCloseAll.Location = new Point(x + 206, y); btnCloseAll.Size = new Size(130, 40); btnCloseAll.Click += new EventHandler(CloseAllClick); this.Controls.Add(btnCloseAll); btnHide = new Button(); btnHide.Text = "隐藏本窗(留贴图)"; btnHide.Location = new Point(x + 352, y); btnHide.Size = new Size(160, 40); btnHide.Click += new EventHandler(delegate { this.Hide(); }); this.Controls.Add(btnHide); y += 62; Label l2 = new Label(); l2.Text = "贴图操作:拖动移动 · 滚轮缩放(20%~500%)· Ctrl+滚轮调透明度 · 双击或 Esc 关闭 · 右键可复制 / 存 PNG"; l2.Location = new Point(x, y); l2.AutoSize = true; this.Controls.Add(l2); y += 34; lblCount = new Label(); lblCount.Text = "当前贴图:0 张"; lblCount.Location = new Point(x, y); lblCount.AutoSize = true; this.Controls.Add(lblCount); y += 34; lblStatus = new Label(); lblStatus.Text = "贴图是置顶悬浮窗,会盖在大多数程序上面;全屏游戏或部分系统界面可能盖不住它,属系统限制。"; lblStatus.Location = new Point(x, y); lblStatus.AutoSize = true; lblStatus.ForeColor = Color.FromArgb(120, 130, 124); this.Controls.Add(lblStatus); NotifyIcon tray = new NotifyIcon(); tray.Icon = SystemIcons.Application; tray.Text = "截图贴图 - 绿色工具箱"; tray.Visible = true; ContextMenuStrip tm = new ContextMenuStrip(); tm.Items.Add("贴一张", null, new EventHandler(delegate { DoPin(); })); tm.Items.Add("显示主窗", null, new EventHandler(delegate { this.Show(); this.WindowState = FormWindowState.Normal; })); tm.Items.Add("关闭全部贴图", null, new EventHandler(delegate { CloseAllPins(); })); tm.Items.Add(new ToolStripSeparator()); tm.Items.Add("退出", null, new EventHandler(delegate { this.Close(); })); tray.ContextMenuStrip = tm; tray.DoubleClick += new EventHandler(delegate { this.Show(); this.WindowState = FormWindowState.Normal; }); } protected override void WndProc(ref Message m) { if (m.Msg == WM_HOTKEY && m.WParam.ToInt32() == HOTKEY_PIN) { DoPin(); return; } base.WndProc(ref m); } protected override void OnShown(EventArgs e) { base.OnShown(e); bool ok = RegisterHotKey(this.Handle, HOTKEY_PIN, MOD_CONTROL | MOD_ALT, (uint)'S'); if (!ok) { lblStatus.Text = "热键 Ctrl+Alt+S 被其它程序占用,仍可用本窗按钮或托盘菜单贴图。"; } } protected override void OnFormClosed(FormClosedEventArgs e) { UnregisterHotKey(this.Handle, HOTKEY_PIN); CloseAllPins(); base.OnFormClosed(e); } public int CountPins() { int n = 0; foreach (Form f in Application.OpenForms) { if (f is PinForm) n++; } return n; } private void UpdateCount() { lblCount.Text = "当前贴图:" + CountPins() + " 张"; } private void PinClick(object sender, EventArgs e) { DoPin(); } private void DoPin() { if (hook != null) { hook.OnPin(this); // 自测:只截屏不弹遮罩 UpdateCount(); return; } this.Hide(); Application.DoEvents(); System.Threading.Thread.Sleep(250); // 等主窗真的消失,避免贴进主窗自己 Image screen = null; PinOverlay overlay = null; try { screen = PinOps.CaptureScreen(); overlay = new PinOverlay(screen); overlay.ShowDialog(); if (overlay.Cancelled || overlay.Selected.IsEmpty) { this.Show(); return; } Bitmap shot = PinOps.Crop(screen, overlay.Selected); PinForm pin = new PinForm(shot, overlay.Selected, false); pin.Show(); UpdateCount(); } finally { if (overlay != null) overlay.Dispose(); if (screen != null) screen.Dispose(); } } /* 自测入口:不弹遮罩,直接用 hook.Region 走「截屏→裁剪→创建贴图窗」 */ internal void SimulatePinForTest() { if (hook == null) return; hook.OnPin(this); UpdateCount(); } internal void AddTestPin(Bitmap b, Rectangle r) { PinForm pin = new PinForm(b, r, true); pin.Show(); UpdateCount(); } private void CloseAllClick(object sender, EventArgs e) { CloseAllPins(); } internal void CloseAllPins() { List