// 屏幕标尺 + 取色器 - 绿色工具箱 // C# 5.0 语法,零依赖(P/Invoke user32 为系统自带) // 标尺:无边框置顶窗,拖动移动,右下角调整大小,实时显示像素尺寸 // 取色:窗口跟随鼠标,实时显示屏幕颜色 HEX/RGB,按 Ctrl 锁定并复制 using System; using System.Drawing; using System.Drawing.Imaging; using System.IO; using System.Runtime.InteropServices; using System.Windows.Forms; namespace GreenToolbox { // ---------- 标尺 ---------- public class RulerForm : Form { private Label lblSize; private ContextMenuStrip menu; private bool verticalMode; public RulerForm() { this.FormBorderStyle = FormBorderStyle.None; this.TopMost = true; this.BackColor = Color.FromArgb(0, 145, 88); this.Opacity = 0.85; this.Size = new Size(400, 60); this.StartPosition = FormStartPosition.Manual; this.Location = new Point(200, 200); this.ShowInTaskbar = false; lblSize = new Label(); lblSize.Dock = DockStyle.Fill; lblSize.TextAlign = ContentAlignment.MiddleCenter; lblSize.Font = new Font("Consolas", 11f, FontStyle.Bold); lblSize.ForeColor = Color.White; lblSize.BackColor = Color.Transparent; this.Controls.Add(lblSize); menu = new ContextMenuStrip(); menu.Items.Add("水平 / 垂直切换", null, new EventHandler(ToggleV)); menu.Items.Add("恢复默认大小 400x60", null, new EventHandler(ResetSize)); menu.Items.Add(new ToolStripSeparator()); menu.Items.Add("打开取色器", null, new EventHandler(OpenPicker)); menu.Items.Add("退出标尺", null, new EventHandler(Quit)); this.MouseClick += new MouseEventHandler(OnMouseClick); this.MouseDown += new MouseEventHandler(OnMouseDown); this.MouseMove += new MouseEventHandler(OnMouseMove); this.Resize += new EventHandler(OnResize); UpdateSize(); } private Point dragStart; private bool dragging; private void OnMouseDown(object sender, MouseEventArgs e) { if (e.Button == MouseButtons.Left) { dragging = true; dragStart = e.Location; } } private void OnMouseMove(object sender, MouseEventArgs e) { if (dragging) { Point s = this.Location; this.Location = new Point(s.X + e.X - dragStart.X, s.Y + e.Y - dragStart.Y); } } private void OnMouseClick(object sender, MouseEventArgs e) { if (e.Button == MouseButtons.Right) menu.Show(this, e.Location); } private void OnResize(object sender, EventArgs e) { UpdateSize(); } private void UpdateSize() { lblSize.Text = RulerOps.SizeText(this.Width, this.Height); } private void ToggleV(object sender, EventArgs e) { verticalMode = !verticalMode; this.Size = RulerOps.ToggleVertical(this.Size, verticalMode); } private void ResetSize(object sender, EventArgs e) { verticalMode = false; this.Size = new Size(400, 60); } private void OpenPicker(object sender, EventArgs e) { new PickerForm().Show(); } private void Quit(object sender, EventArgs e) { this.Close(); } } // ---------- 取色器 ---------- public class PickerForm : Form { [DllImport("user32.dll")] private static extern bool GetCursorPos(out POINT p); [DllImport("user32.dll")] private static extern short GetAsyncKeyState(int vKey); [DllImport("user32.dll")] private static extern IntPtr GetDC(IntPtr hwnd); [DllImport("user32.dll")] private static extern int ReleaseDC(IntPtr hwnd, IntPtr hdc); [StructLayout(LayoutKind.Sequential)] private struct POINT { public int X; public int Y; } private const int VK_CONTROL = 0x11; private Label lblColor; private Label lblHex; private Label lblRgb; private Panel preview; private Timer timer; private PictureBox magnifier; private string lockedHex = ""; public PickerForm() { this.Text = "屏幕取色器 - 绿色工具箱"; this.Font = new Font("Microsoft YaHei UI", 9.5f); this.BackColor = Color.White; this.ClientSize = new Size(300, 330); this.TopMost = true; this.ShowInTaskbar = false; this.FormBorderStyle = FormBorderStyle.FixedSingle; this.MaximizeBox = false; Label l0 = new Label(); l0.Text = "窗口跟随鼠标,按住 Ctrl 锁定颜色并复制"; l0.AutoSize = true; l0.ForeColor = Color.FromArgb(120, 130, 124); l0.Location = new Point(16, 12); this.Controls.Add(l0); magnifier = new PictureBox(); magnifier.Location = new Point(16, 38); magnifier.Size = new Size(120, 120); magnifier.BorderStyle = BorderStyle.FixedSingle; magnifier.SizeMode = PictureBoxSizeMode.StretchImage; this.Controls.Add(magnifier); preview = new Panel(); preview.Location = new Point(150, 38); preview.Size = new Size(134, 120); preview.BorderStyle = BorderStyle.FixedSingle; this.Controls.Add(preview); lblHex = new Label(); lblHex.Text = "HEX: #------"; lblHex.Font = new Font("Consolas", 12f, FontStyle.Bold); lblHex.Location = new Point(16, 172); lblHex.AutoSize = true; this.Controls.Add(lblHex); lblRgb = new Label(); lblRgb.Text = "RGB: ---, ---, ---"; lblRgb.Font = new Font("Consolas", 10f); lblRgb.Location = new Point(16, 200); lblRgb.AutoSize = true; this.Controls.Add(lblRgb); lblColor = new Label(); lblColor.Text = ""; lblColor.Location = new Point(16, 228); lblColor.AutoSize = true; lblColor.ForeColor = Color.FromArgb(120, 130, 124); this.Controls.Add(lblColor); Label l1 = new Label(); l1.Text = "最近锁定:"; l1.AutoSize = true; l1.ForeColor = Color.FromArgb(120, 130, 124); l1.Location = new Point(16, 262); this.Controls.Add(l1); timer = new Timer(); timer.Interval = 60; timer.Tick += new EventHandler(Tick); timer.Start(); this.FormClosed += new FormClosedEventHandler(delegate(object s, FormClosedEventArgs e2) { timer.Stop(); }); } private void Tick(object sender, EventArgs e) { POINT p; GetCursorPos(out p); IntPtr dc = GetDC(IntPtr.Zero); Color c = ColorTranslator.FromWin32((int)GetPixel(dc, p.X, p.Y)); ReleaseDC(IntPtr.Zero, dc); preview.BackColor = c; string hex = RulerOps.Hex(c); lblHex.Text = "HEX: " + hex; lblRgb.Text = "RGB: " + RulerOps.RgbText(c); // 放大镜:取鼠标周围 24x24 像素放大 try { // 不能写在 using 里:赋给 PictureBox 后 using 会把位图 Dispose 掉, // 下一次重绘就在已释放的 Image 上抛「参数无效」。改成换图时手动释放上一张。 Bitmap bmp = new Bitmap(24, 24, PixelFormat.Format32bppArgb); using (Graphics g = Graphics.FromImage(bmp)) { g.CopyFromScreen(p.X - 12, p.Y - 12, 0, 0, new Size(24, 24)); } Image oldImg = magnifier.Image; magnifier.Image = bmp; if (oldImg != null) oldImg.Dispose(); } catch { } // Ctrl 锁定 if (RulerOps.IsKeyDown(GetAsyncKeyState(VK_CONTROL))) { if (lockedHex != hex) { lockedHex = hex; try { Clipboard.SetText(hex); } catch { } lblColor.Text = "已锁定 " + hex + "(已复制)"; } } } [DllImport("gdi32.dll")] private static extern uint GetPixel(IntPtr hdc, int x, int y); } // ── 与界面解耦的纯逻辑,--selftest 直接调这里 ───────────────────────── public static class RulerOps { public static string Hex(Color c) { return "#" + c.R.ToString("X2") + c.G.ToString("X2") + c.B.ToString("X2"); } public static string RgbText(Color c) { return c.R + ", " + c.G + ", " + c.B; } public static string SizeText(int w, int h) { return w + " × " + h + " px"; } // 横竖切换:长边(用户拉出来的长度)要留住,短边固定 60,且至少 400 // 原来的写法取的是「切换后那个方向的当前值」,横条 800 宽切竖条会缩回 400 高 public static Size ToggleVertical(Size cur, bool vertical) { int len = Math.Max(Math.Max(cur.Width, cur.Height), 400); if (vertical) return new Size(60, len); return new Size(len, 60); } // GetAsyncKeyState 的最高位是「当前按下」 public static bool IsKeyDown(short state) { return (state & 0x8000) != 0; } } static class Program { [STAThread] static void Main(string[] args) { if (args != null && args.Length > 0 && args[0] == "--selftest") { Environment.Exit(SelfTest.Run(args.Length >= 2 ? args[1] : null)); } Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); if (args != null && args.Length > 0 && args[0] == "--picker") Application.Run(new PickerForm()); else Application.Run(new RulerForm()); } } // 命令行自测:不弹窗,纯逻辑跑一遍,退出码 0 = 全过,1 = 有失败 public static class SelfTest { private static int _pass = 0; private static int _fail = 0; private static System.Collections.Generic.List _lines = new System.Collections.Generic.List(); private static string Esc(string s) { if (s == null) return ""; return s.Replace("\r", "\\r").Replace("\n", "\\n"); } private static void Check(string name, string got, string want) { if (got == null) got = ""; if (want == null) want = ""; if (got == want) { _pass++; _lines.Add(" [ok] " + name); } else { _fail++; _lines.Add(" [!!] " + name + " 期望[" + Esc(want) + "] 实际[" + Esc(got) + "]"); } } private static void CheckSize(string name, Size got, int w, int h) { Check(name, got.Width + "x" + got.Height, w + "x" + h); } public static int Run(string dir) { try { _lines.Add("屏幕标尺取色 自测"); // ── 颜色文案 ── Check("品牌绿转 HEX", RulerOps.Hex(Color.FromArgb(0, 145, 88)), "#009158"); Check("黑色", RulerOps.Hex(Color.Black), "#000000"); Check("白色", RulerOps.Hex(Color.White), "#FFFFFF"); Check("单通道补零", RulerOps.Hex(Color.FromArgb(1, 2, 3)), "#010203"); Check("RGB 文案", RulerOps.RgbText(Color.FromArgb(0, 145, 88)), "0, 145, 88"); Check("RGB 文案(黑)", RulerOps.RgbText(Color.Black), "0, 0, 0"); // ── Win32 COLORREF 是 0x00BBGGRR,通道顺序最容易搞反 ── Check("COLORREF 0x0000FF 是纯红(不是蓝)", RulerOps.Hex(ColorTranslator.FromWin32(0x0000FF)), "#FF0000"); Check("COLORREF 0xFF0000 是纯蓝", RulerOps.Hex(ColorTranslator.FromWin32(0xFF0000)), "#0000FF"); Check("COLORREF 0x009158 → BGR 顺序还原", RulerOps.Hex(ColorTranslator.FromWin32(0x589100)), "#009158"); // ── 尺寸文案 ── Check("默认尺寸文案", RulerOps.SizeText(400, 60), "400 × 60 px"); Check("1 像素也照实显示", RulerOps.SizeText(1, 1), "1 × 1 px"); // ── 横竖切换 ── CheckSize("默认横条 → 竖条", RulerOps.ToggleVertical(new Size(400, 60), true), 60, 400); CheckSize("矮横条切竖条也够 400 高", RulerOps.ToggleVertical(new Size(800, 60), true), 60, 800); CheckSize("竖条 → 横条", RulerOps.ToggleVertical(new Size(60, 400), false), 400, 60); CheckSize("长竖条切横条保留长度", RulerOps.ToggleVertical(new Size(60, 900), false), 900, 60); // ── Ctrl 按下判定 ── Check("最高位为 1 表示按下", RulerOps.IsKeyDown(unchecked((short)0x8000)) ? "down" : "up", "down"); Check("最高位为 0 表示没按", RulerOps.IsKeyDown(0) ? "down" : "up", "up"); Check("低位噪声不影响判定", RulerOps.IsKeyDown(unchecked((short)0x8001)) ? "down" : "up", "down"); } catch (Exception ex) { _fail++; _lines.Add(" [!!] 自测中途异常:" + ex.GetType().Name + " " + ex.Message); } _lines.Add(""); if (_fail == 0) _lines.Add("结果:共 " + (_pass + _fail) + " 项,全部通过 ✓"); else _lines.Add("结果:共 " + (_pass + _fail) + " 项,通过 " + _pass + ",失败 " + _fail + " ✗"); string all = string.Join("\r\n", _lines.ToArray()); Console.WriteLine(all); try { File.WriteAllText(Path.Combine(Directory.GetCurrentDirectory(), "selftest-ruler.txt"), all, new System.Text.UTF8Encoding(true)); } catch { } return _fail == 0 ? 0 : 1; } } }