// 屏幕取色器 - 绿色工具箱 // C# 5.0 语法,零依赖(只用 System.Drawing / WinForms) // 定位:设计师/前端刚需。全屏冻结取色 + 放大镜 + HEX/RGB/HSL 一键复制 + 历史记录 using System; using System.Collections.Generic; using System.Drawing; using System.Drawing.Drawing2D; using System.Globalization; using System.Windows.Forms; namespace GreenToolbox { // ===== 纯函数区(可自测,不碰界面) ===== public static class PickOps { // #RRGGBB,永远小写、带 #,前端直接能用 public static string ToHex(Color c) { return "#" + c.R.ToString("x2", CultureInfo.InvariantCulture) + c.G.ToString("x2", CultureInfo.InvariantCulture) + c.B.ToString("x2", CultureInfo.InvariantCulture); } // 认 #RGB / #RRGGBB,带不带 # 都行;非法返回 null public static Color? ParseHex(string s) { if (string.IsNullOrEmpty(s)) return null; s = s.Trim(); if (s.StartsWith("#")) s = s.Substring(1); if (s.Length == 3) { int r, g, b; if (TryHex2(s[0], s[0], out r) && TryHex2(s[1], s[1], out g) && TryHex2(s[2], s[2], out b)) return Color.FromArgb(r, g, b); return null; } if (s.Length == 6) { int r, g, b; if (TryHex2(s[0], s[1], out r) && TryHex2(s[2], s[3], out g) && TryHex2(s[4], s[5], out b)) return Color.FromArgb(r, g, b); return null; } return null; } static bool TryHex2(char hi, char lo, out int val) { int h = HexVal(hi), l = HexVal(lo); if (h < 0 || l < 0) { val = 0; return false; } val = h * 16 + l; return true; } static int HexVal(char c) { if (c >= '0' && c <= '9') return c - '0'; if (c >= 'a' && c <= 'f') return c - 'a' + 10; if (c >= 'A' && c <= 'F') return c - 'A' + 10; return -1; } // CSS 写法:rgb(255, 128, 0) public static string ToCssRgb(Color c) { return "rgb(" + c.R + ", " + c.G + ", " + c.B + ")"; } // h ∈ [0,360), s/l ∈ [0,100] public static void RgbToHsl(Color c, out double h, out double s, out double l) { double r = c.R / 255.0, g = c.G / 255.0, b = c.B / 255.0; double max = Math.Max(r, Math.Max(g, b)); double min = Math.Min(r, Math.Min(g, b)); l = (max + min) / 2.0; if (max == min) { h = 0; s = 0; return; } double d = max - min; s = l > 0.5 ? d / (2.0 - max - min) : d / (max + min); if (max == r) h = (g - b) / d + (g < b ? 6.0 : 0.0); else if (max == g) h = (b - r) / d + 2.0; else h = (r - g) / d + 4.0; h *= 60.0; } public static Color HslToRgb(double h, double s, double l) { h = ((h % 360.0) + 360.0) % 360.0; s = Clamp01(s); l = Clamp01(l); if (s == 0) { int v = (int)Math.Round(l * 255.0); return Color.FromArgb(v, v, v); } double q = l < 0.5 ? l * (1.0 + s) : l + s - l * s; double p = 2.0 * l - q; return Color.FromArgb(Hue(p, q, h / 360.0 + 1.0 / 3.0), Hue(p, q, h / 360.0), Hue(p, q, h / 360.0 - 1.0 / 3.0)); } static int Hue(double p, double q, double t) { if (t < 0) t += 1.0; if (t > 1) t -= 1.0; double d; if (t < 1.0 / 6.0) d = p + (q - p) * 6.0 * t; else if (t < 0.5) d = q; else if (t < 2.0 / 3.0) d = p + (q - p) * (2.0 / 3.0 - t) * 6.0; else d = p; return (int)Math.Round(d * 255.0); } static double Clamp01(double v) { return v < 0 ? 0 : (v > 1 ? 1 : v); } // 相对亮度(WCAG),用于判断该配黑字还是白字 public static double Luminance(Color c) { double r = Lin(c.R), g = Lin(c.G), b = Lin(c.B); return 0.2126 * r + 0.7152 * g + 0.0722 * b; } static double Lin(int v) { double x = v / 255.0; return x <= 0.03928 ? x / 12.92 : Math.Pow((x + 0.055) / 1.055, 2.4); } // 深色底配白字、浅色底配黑字 public static Color ContrastText(Color bg) { return Luminance(bg) > 0.35 ? Color.FromArgb(20, 20, 20) : Color.FromArgb(245, 245, 245); } // 两色对比度(WCAG),1~21 public static double ContrastRatio(Color a, Color b) { double la = Luminance(a), lb = Luminance(b); double hi = la > lb ? la : lb, lo = la > lb ? lb : la; return (hi + 0.05) / (lo + 0.05); } // 放大镜取色:从位图中心读一个像素(坐标越界返回 null) public static Color? PixelAt(System.Drawing.Bitmap bmp, int x, int y) { if (bmp == null) return null; if (x < 0 || y < 0 || x >= bmp.Width || y >= bmp.Height) return null; return bmp.GetPixel(x, y); } // 把历史色格式化成一行:#aabbcc rgb(1,2,3) public static string HistoryLine(Color c) { return ToHex(c) + " " + ToCssRgb(c); } // 从历史文本行解析回颜色(复制回来的hex可直接用) public static Color? FromHistoryLine(string line) { if (string.IsNullOrEmpty(line)) return null; string head = line.Trim(); int sp = head.IndexOf(' '); if (sp > 0) head = head.Substring(0, sp); return ParseHex(head); } } // ===== 取色覆盖层:冻结全屏 + 放大镜,点一下取色,Esc 取消 ===== public class PickOverlay : Form { Bitmap _shot; Point _mouse; bool _picked; Color _result; const int ZOOM = 17; // 17x17 像素 const int CELL = 22; // 每格 22px public bool Picked { get { return _picked; } } public Color Result { get { return _result; } } public PickOverlay(Bitmap shot) { _shot = shot; FormBorderStyle = FormBorderStyle.None; StartPosition = FormStartPosition.Manual; Bounds = SystemInformation.VirtualScreen; TopMost = true; Cursor = Cursors.Cross; KeyPreview = true; DoubleBuffered = true; KeyDown += (s, e) => { if (e.KeyCode == Keys.Escape) { _picked = false; Close(); } }; MouseMove += (s, e) => { _mouse = e.Location; Invalidate(); }; MouseClick += (s, e) => { if (e.Button != MouseButtons.Left) return; int sx = e.X + SystemInformation.VirtualScreen.Left; int sy = e.Y + SystemInformation.VirtualScreen.Top; Color? c = PickOps.PixelAt(_shot, sx, sy); if (c.HasValue) { _result = c.Value; _picked = true; } Close(); }; Paint += OnPaint; } void OnPaint(object s, PaintEventArgs e) { Graphics g = e.Graphics; g.PixelOffsetMode = PixelOffsetMode.Half; // 放大镜面板(跟随鼠标,别出屏) int size = ZOOM * CELL; int px = _mouse.X + 24, py = _mouse.Y + 24; if (px + size > Width) px = _mouse.X - size - 24; if (py + size + 34 > Height) py = _mouse.Y - size - 34 - 24; if (px < 0) px = 0; if (py < 0) py = 0; using (SolidBrush back = new SolidBrush(Color.FromArgb(230, 245, 245, 245))) g.FillRectangle(back, px - 4, py - 4, size + 8, size + 8); g.DrawRectangle(Pens.Gray, px - 4, py - 4, size + 8, size + 8); // 17x17 邻域逐格画 int cx = _mouse.X + SystemInformation.VirtualScreen.Left; int cy = _mouse.Y + SystemInformation.VirtualScreen.Top; int half = ZOOM / 2; for (int dy = -half; dy <= half; dy++) { for (int dx = -half; dx <= half; dx++) { Color? c = PickOps.PixelAt(_shot, cx + dx, cy + dy); Color col = c.HasValue ? c.Value : Color.White; using (SolidBrush br = new SolidBrush(col)) g.FillRectangle(br, px + (dx + half) * CELL, py + (dy + half) * CELL, CELL, CELL); } } // 中心十字 using (Pen red = new Pen(Color.FromArgb(220, 220, 30, 30), 2)) { g.DrawRectangle(red, px + half * CELL, py + half * CELL, CELL - 1, CELL - 1); } // 底部色值条 Color? cur = PickOps.PixelAt(_shot, cx, cy); if (cur.HasValue) { string txt = PickOps.ToHex(cur.Value) + " " + PickOps.ToCssRgb(cur.Value); Font f = new Font("Consolas", 14, FontStyle.Bold); SizeF ts = g.MeasureString(txt, f); using (SolidBrush bb = new SolidBrush(cur.Value)) g.FillRectangle(bb, px - 4, py + size + 8, size + 8, ts.Height + 10); using (SolidBrush tb = new SolidBrush(PickOps.ContrastText(cur.Value))) g.DrawString(txt, f, tb, px + 4, py + size + 12); } } } // ===== 主窗口 ===== public class PickForm : Form { Panel _preview; Label _lbHex, _lbRgb, _lbHsl, _lbLum; ListBox _hist; Button _btnPick; Color _cur = Color.FromArgb(66, 133, 244); List _history = new List(); public PickForm() { Text = "屏幕取色器 - 绿色工具箱"; FormBorderStyle = FormBorderStyle.FixedSingle; MaximizeBox = false; StartPosition = FormStartPosition.CenterScreen; ClientSize = new Size(560, 430); Font = new Font("Microsoft YaHei UI", 9F); Label tip = new Label(); tip.Text = "点「开始取色」,屏幕会冻结并出现放大镜,移动到目标处单击取色,Esc 取消。"; tip.ForeColor = Color.DimGray; tip.SetBounds(16, 12, 520, 20); Controls.Add(tip); _preview = new Panel(); _preview.SetBounds(16, 40, 120, 120); _preview.BorderStyle = BorderStyle.FixedSingle; _preview.Paint += (s, e) => { using (SolidBrush br = new SolidBrush(_cur)) e.Graphics.FillRectangle(br, 0, 0, 120, 120); using (SolidBrush tb = new SolidBrush(PickOps.ContrastText(_cur))) e.Graphics.DrawString(PickOps.ToHex(_cur), new Font("Consolas", 10, FontStyle.Bold), tb, 8, 96); }; Controls.Add(_preview); _btnPick = new Button(); _btnPick.Text = "开始取色"; _btnPick.SetBounds(152, 40, 110, 32); _btnPick.Click += (s, e) => StartPick(); Controls.Add(_btnPick); _lbHex = MakeLabel(152, 84); _lbRgb = MakeLabel(152, 112); _lbHsl = MakeLabel(152, 140); _lbLum = MakeLabel(152, 168); Button cpHex = new Button(); cpHex.Text = "复制 HEX"; cpHex.SetBounds(300, 80, 90, 26); cpHex.Click += (s, e) => Copy(PickOps.ToHex(_cur)); Button cpRgb = new Button(); cpRgb.Text = "复制 RGB"; cpRgb.SetBounds(398, 80, 90, 26); cpRgb.Click += (s, e) => Copy(PickOps.ToCssRgb(_cur)); Button cpHsl = new Button(); cpHsl.Text = "复制 HSL"; cpHsl.SetBounds(300, 108, 90, 26); cpHsl.Click += (s, e) => { double h, ss, l; PickOps.RgbToHsl(_cur, out h, out ss, out l); Copy("hsl(" + Math.Round(h) + ", " + Math.Round(ss * 100) + "%, " + Math.Round(l * 100) + "%)"); }; Button cpInt = new Button(); cpInt.Text = "复制 BGR"; cpInt.SetBounds(398, 108, 90, 26); cpInt.Click += (s, e) => Copy(_cur.ToArgb().ToString(CultureInfo.InvariantCulture)); Controls.Add(cpHex); Controls.Add(cpRgb); Controls.Add(cpHsl); Controls.Add(cpInt); Label lh = new Label(); lh.Text = "取色历史(双击重新选中):"; lh.SetBounds(16, 214, 300, 20); Controls.Add(lh); _hist = new ListBox(); _hist.SetBounds(16, 238, 520, 150); _hist.Font = new Font("Consolas", 10F); _hist.DoubleClick += (s, e) => { Color? c = PickOps.FromHistoryLine(_hist.Text); if (c.HasValue) SetColor(c.Value); }; Controls.Add(_hist); Button clr = new Button(); clr.Text = "清空历史"; clr.SetBounds(446, 398, 90, 26); clr.Click += (s, e) => { _history.Clear(); _hist.Items.Clear(); }; Controls.Add(clr); SetColor(_cur); } Label MakeLabel(int x, int y) { Label l = new Label(); l.Font = new Font("Consolas", 9.5F); l.SetBounds(x, y, 146, 24); Controls.Add(l); return l; } void Copy(string text) { if (string.IsNullOrEmpty(text)) return; try { Clipboard.SetText(text); } catch { } } void SetColor(Color c) { _cur = c; _lbHex.Text = PickOps.ToHex(c); _lbRgb.Text = PickOps.ToCssRgb(c); double h, s, l; PickOps.RgbToHsl(c, out h, out s, out l); _lbHsl.Text = "hsl(" + Math.Round(h) + ", " + Math.Round(s * 100) + "%, " + Math.Round(l * 100) + "%)"; _lbLum.Text = "亮度 " + PickOps.Luminance(c).ToString("F3", CultureInfo.InvariantCulture); _preview.Invalidate(); } void StartPick() { Rectangle vs = SystemInformation.VirtualScreen; Bitmap shot = new Bitmap(vs.Width, vs.Height); using (Graphics g = Graphics.FromImage(shot)) g.CopyFromScreen(vs.Left, vs.Top, 0, 0, vs.Size); Color got = Color.Empty; using (PickOverlay ov = new PickOverlay(shot)) { ov.ShowDialog(this); if (ov.Picked) got = ov.Result; } shot.Dispose(); if (!got.IsEmpty) { SetColor(got); // 去重:连续取同一个色不重复记 if (!(_history.Count > 0 && _history[_history.Count - 1].ToArgb() == got.ToArgb())) { _history.Add(got); _hist.Items.Insert(0, PickOps.HistoryLine(got)); } Copy(PickOps.ToHex(got)); // 取完顺手复制,少点一次 } } } public static class ColorPickProgram { [STAThread] public static void Main(string[] args) { if (args != null && args.Length >= 1 && args[0] == "--selftest") { Environment.Exit(SelfTest.RunAll()); } Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new PickForm()); } } // ===== 自测 ===== public static class SelfTest { static int _fail; static void Check(bool ok, string name) { Console.WriteLine((ok ? "[PASS] " : "[FAIL] ") + name); if (!ok) _fail++; } public static int RunAll() { // --- HEX 往返 --- Check(PickOps.ToHex(Color.FromArgb(255, 0, 0)) == "#ff0000", "ToHex 纯红"); Check(PickOps.ToHex(Color.FromArgb(0x0a, 0x1b, 0x2c)) == "#0a1b2c", "ToHex 补零"); Check(PickOps.ParseHex("#FF8800").Value.ToArgb() == Color.FromArgb(255, 136, 0).ToArgb(), "ParseHex 大写带#"); Check(PickOps.ParseHex("f80").Value.ToArgb() == Color.FromArgb(255, 136, 0).ToArgb(), "ParseHex 3位短写"); Check(PickOps.ParseHex("abc") .Value.ToArgb() == Color.FromArgb(170, 187, 204).ToArgb(), "ParseHex 无#短写"); Check(PickOps.ParseHex("#12345").HasValue == false, "ParseHex 5位非法"); Check(PickOps.ParseHex("#gggggg").HasValue == false, "ParseHex 非法字符"); Check(PickOps.ParseHex("").HasValue == false, "ParseHex 空串"); Check(PickOps.ParseHex(null).HasValue == false, "ParseHex null"); Check(PickOps.ParseHex(" #A1B2C3 ").Value.R == 0xa1, "ParseHex 带空格"); // --- CSS RGB --- Check(PickOps.ToCssRgb(Color.FromArgb(255, 128, 0)) == "rgb(255, 128, 0)", "ToCssRgb 格式"); // --- HSL 往返 --- double h, s, l; PickOps.RgbToHsl(Color.FromArgb(255, 0, 0), out h, out s, out l); Check(Math.Abs(h) < 1e-9 && Math.Abs(s - 1) < 1e-9 && Math.Abs(l - 0.5) < 1e-9, "Hsl 红=0,100%,50%"); PickOps.RgbToHsl(Color.FromArgb(255, 255, 255), out h, out s, out l); Check(s == 0 && Math.Abs(l - 1) < 1e-9, "Hsl 白 s=0 l=100"); PickOps.RgbToHsl(Color.FromArgb(0, 0, 0), out h, out s, out l); Check(s == 0 && l == 0, "Hsl 黑 s=0 l=0"); PickOps.RgbToHsl(Color.FromArgb(0, 128, 255), out h, out s, out l); Check(Math.Abs(h - 210) < 0.5, "Hsl 蓝色相210"); Color back = PickOps.HslToRgb(210, 1.0, 0.5); Check(back.R == 0 && Math.Abs(back.G - 128) <= 1 && back.B == 255, "HslToRgb 往返蓝"); Color back2 = PickOps.HslToRgb(0, 1.0, 0.5); Check(back2.R == 255 && back2.G == 0 && back2.B == 0, "HslToRgb 往返红"); Color gray = PickOps.HslToRgb(123, 0, 0.5); Check(gray.R == 128 && gray.G == 128 && gray.B == 128, "HslToRgb s=0 出灰"); Color wrap = PickOps.HslToRgb(420, 1.0, 0.5); // 420 = 60 Check(wrap.R == 255 && wrap.G == 255 && wrap.B == 0, "HslToRgb 色相环绕420"); Color neg = PickOps.HslToRgb(-30, 1.0, 0.5); // -30 = 330 Check(neg.R == 255 && neg.G == 0 && neg.B == 128, "HslToRgb 负色相-30"); // --- 亮度/对比度 --- Check(Math.Abs(PickOps.Luminance(Color.FromArgb(255, 255, 255)) - 1.0) < 1e-9, "Luminance 白=1"); Check(Math.Abs(PickOps.Luminance(Color.FromArgb(0, 0, 0))) < 1e-9, "Luminance 黑=0"); Check(PickOps.ContrastText(Color.FromArgb(255, 255, 255)) == Color.FromArgb(20, 20, 20), "白底配黑字"); Check(PickOps.ContrastText(Color.FromArgb(0, 0, 0)) == Color.FromArgb(245, 245, 245), "黑底配白字"); Check(Math.Abs(PickOps.ContrastRatio(Color.Black, Color.White) - 21.0) < 0.01, "黑白对比度=21"); Check(Math.Abs(PickOps.ContrastRatio(Color.White, Color.White) - 1.0) < 1e-9, "同色对比度=1"); Check(PickOps.ContrastRatio(Color.White, Color.Black) == PickOps.ContrastRatio(Color.Black, Color.White), "对比度对称"); // --- 放大镜取像素 --- using (Bitmap bmp = new Bitmap(10, 10)) { bmp.SetPixel(3, 4, Color.FromArgb(1, 2, 3)); Color? c1 = PickOps.PixelAt(bmp, 3, 4); Check(c1.HasValue && c1.Value.R == 1 && c1.Value.G == 2 && c1.Value.B == 3, "PixelAt 命中"); Check(PickOps.PixelAt(bmp, -1, 0).HasValue == false, "PixelAt 负坐标"); Check(PickOps.PixelAt(bmp, 10, 0).HasValue == false, "PixelAt 越界右"); Check(PickOps.PixelAt(bmp, 0, 10).HasValue == false, "PixelAt 越界下"); Check(PickOps.PixelAt(null, 0, 0).HasValue == false, "PixelAt 空位图"); } // --- 历史行往返 --- Color hc = Color.FromArgb(0x12, 0x34, 0x56); string line = PickOps.HistoryLine(hc); Check(line == "#123456 rgb(18, 52, 86)", "HistoryLine 格式"); Color? hb = PickOps.FromHistoryLine(line); Check(hb.HasValue && hb.Value.R == 0x12 && hb.Value.G == 0x34 && hb.Value.B == 0x56, "FromHistoryLine 解析"); Check(PickOps.FromHistoryLine("#aabbcc").Value.R == 0xaa, "FromHistoryLine 纯hex"); Check(PickOps.FromHistoryLine("垃圾文本").HasValue == false, "FromHistoryLine 垃圾输入"); Check(PickOps.FromHistoryLine(null).HasValue == false, "FromHistoryLine null"); Console.WriteLine("selftest: " + (_fail == 0 ? "ALL PASS" : _fail + " FAILED")); return _fail == 0 ? 0 : 1; } } }