// 截图贴图 - 绿色工具箱 // 单文件零依赖,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
dead = new List(); foreach (Form f in Application.OpenForms) { if (f is PinForm) dead.Add(f); } foreach (Form f in dead) f.Close(); UpdateCount(); } } // ───────────────────────── 自测 ───────────────────────── public static class SnapPinSelfTest { public class HookForTest { public Rectangle Region; public string LastFile; public int PinsCreated; public void OnPin(SnapPinForm form) { using (Image screen = PinOps.CaptureScreen()) { Bitmap shot = PinOps.Crop(screen, Region); form.AddTestPin(shot, Region); PinsCreated++; } } } 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-snappin-" + Guid.NewGuid().ToString("N").Substring(0, 8)) : dir; try { Directory.CreateDirectory(baseDir); // 几何:反向拖拽归一、误触判定 Rectangle r = PinOps.Normalize(new Point(500, 400), new Point(100, 120)); Check("反向拖拽归一", r.X + "," + r.Y + "," + r.Width + "," + r.Height, "100,120,400,280"); Check("同点没意义", PinOps.IsMeaningful(PinOps.Normalize(new Point(7, 7), new Point(7, 7))), false); Check("3×5 太小算误触", PinOps.IsMeaningful(new Rectangle(0, 0, 3, 5)), false); Check("正常选区有意义", PinOps.IsMeaningful(new Rectangle(0, 0, 640, 480)), true); // 缩放:夹取边界 Check("缩放下限", PinOps.ClampZoom(0.01), 0.2); Check("缩放上限", PinOps.ClampZoom(99), 5.0); Check("正常倍率保留", PinOps.ClampZoom(1.5), 1.5); Check("上滚放大", Math.Round(PinOps.StepZoom(1.0, 120), 4), Math.Round(1.1, 4)); Check("下滚缩小", Math.Round(PinOps.StepZoom(1.1, -120), 4), Math.Round(1.0, 4)); Check("缩小到底不再变", PinOps.StepZoom(0.2, -120), 0.2); Check("放大到顶不再变", PinOps.StepZoom(5.0, 120), 5.0); // 光标锚缩放:光标下的点不动 Point loc = PinOps.ZoomedLocation(new Point(100, 50), new Point(80, 40), 1.0, 2.0); Check("锚缩放 1→2", loc.X + "," + loc.Y, "60,30"); Point loc2 = PinOps.ZoomedLocation(new Point(60, 30), new Point(60, 30), 2.0, 1.0); Check("锚在左上角不动", loc2.X + "," + loc2.Y, "60,30"); Point loc3 = PinOps.ZoomedLocation(new Point(200, 200), new Point(150, 150), 2.0, 4.0); Check("锚缩放 2→4", loc3.X + "," + loc3.Y, "100,100"); // 光标指着画面同一点:缩放后该画面点仍应位于光标处 Point cursor = new Point(300, 200); Point oldLoc = new Point(120, 90); double oz = 1.0, nz = 1.32; Point newLoc = PinOps.ZoomedLocation(cursor, oldLoc, oz, nz); // 画面点 p = (cursor-loc)/zoom;新位置 cursor' = newLoc + p*newZoom double px = (cursor.X - oldLoc.X) / oz, py = (cursor.Y - oldLoc.Y) / oz; int backX = (int)Math.Round(newLoc.X + px * nz); int backY = (int)Math.Round(newLoc.Y + py * nz); Check("画面点回到光标下", backX + "," + backY, cursor.X + "," + cursor.Y); // 显示尺寸:取整与下限 Size s1 = PinOps.DisplaySize(300, 200, 1.0); Check("1.0 尺寸不变", s1.Width + "x" + s1.Height, "300x200"); Size s2 = PinOps.DisplaySize(300, 200, 0.2); Check("0.2 尺寸", s2.Width + "x" + s2.Height, "60x40"); Size s3 = PinOps.DisplaySize(2, 1, 0.2); Check("极小图至少 1px", s3.Width + "x" + s3.Height, "1x1"); // 透明度夹取 Check("透明度下限", PinOps.ClampOpacity(0.01), 0.15); Check("透明度上限", PinOps.ClampOpacity(1.7), 1.0); Check("正常透明度保留", PinOps.ClampOpacity(0.55), 0.55); Check("Ctrl 上滚变实", PinOps.ClampOpacity(0.9 + 0.1), 1.0); // 保存链路:合成 320×240 渐变图存 PNG 并读回 using (Bitmap bmp = new Bitmap(320, 240, PixelFormat.Format32bppArgb)) { using (Graphics g = Graphics.FromImage(bmp)) { using (LinearGradientBrush br = new LinearGradientBrush( new Rectangle(0, 0, 320, 240), Color.FromArgb(0, 145, 88), Color.White, 45f)) { g.FillRectangle(br, 0, 0, 320, 240); } g.FillEllipse(Brushes.Orange, 110, 70, 100, 100); } string png = Path.Combine(baseDir, "pin1.png"); long n = PinOps.SavePng(bmp, png); Check("PNG 写出", File.Exists(png) && n > 0, true); using (Image back = Image.FromFile(png)) Check("PNG 尺寸", back.Width + "x" + back.Height, "320x240"); } // 文件名去重 string d2 = Path.Combine(baseDir, "names"); Directory.CreateDirectory(d2); string n1 = PinOps.NextName(d2, ".png"); File.WriteAllText(n1, "x"); string n2 = PinOps.NextName(d2, ".png"); Check("重名加 (2)", Path.GetFileName(n1) != Path.GetFileName(n2) && Path.GetFileName(n2).Contains("(2)"), true); Check("前缀是贴图", Path.GetFileName(n1).StartsWith("贴图_"), true); // 真截屏 + 裁剪链路(无头环境有桌面会话,CopyFromScreen 可用) Rectangle vs = SystemInformation.VirtualScreen; Rectangle region = new Rectangle(vs.X + 10, vs.Y + 10, 280, 180); SnapPinForm form = new SnapPinForm(); HookForTest hook = new HookForTest(); hook.Region = region; form.hook = hook; form.SimulatePinForTest(); Check("贴图窗已创建", hook.PinsCreated > 0, true); Check("计数更新", form.CountPins() > 0, true); // 关全部 form.CloseAllPins(); Check("关全部归零", form.CountPins(), 0); 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-snappin.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(SnapPinSelfTest.Run(args.Length >= 2 ? args[1] : null)); } Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new SnapPinForm()); } } }