// 窗口置顶助手 - 绿色工具箱 // 单文件零依赖(仅 Win32 API),C# 5.0 语法 // 功能:列出当前可见窗口,勾选即置顶(永远压在最上层),取消勾选恢复 // 边界:不改窗口大小位置、不注入进程、不隐藏窗口;只操作真实存在且有标题的窗口 // 记忆:可保存「进程名 + 标题」规则,下次打开自动恢复这些窗口的置顶状态 using System; using System.Collections.Generic; using System.Diagnostics; using System.Drawing; using System.IO; using System.Runtime.InteropServices; using System.Text; using System.Windows.Forms; namespace GreenToolbox { public class WinItem { public IntPtr Handle; public string Title; public string Process; public bool TopMost; public string Key { get { return (Process == null ? "" : Process) + "|" + (Title == null ? "" : Title.Trim()); } } } public static class TopMostOps { const int GWL_EXSTYLE = -20; const int WS_EX_TOPMOST = 0x00000008; const uint SWP_NOSIZE = 0x0001; const uint SWP_NOMOVE = 0x0002; const uint SWP_NOACTIVATE = 0x0010; static readonly IntPtr HWND_TOPMOST = new IntPtr(-1); static readonly IntPtr HWND_NOTOPMOST = new IntPtr(-2); delegate bool EnumProc(IntPtr hWnd, IntPtr lParam); [DllImport("user32.dll")] static extern bool EnumWindows(EnumProc cb, IntPtr lParam); [DllImport("user32.dll", CharSet = CharSet.Unicode, EntryPoint = "GetWindowTextW")] static extern int GetWindowText(IntPtr h, StringBuilder sb, int max); [DllImport("user32.dll", CharSet = CharSet.Unicode, EntryPoint = "GetWindowTextLengthW")] static extern int GetWindowTextLength(IntPtr h); [DllImport("user32.dll")] static extern bool IsWindowVisible(IntPtr h); [DllImport("user32.dll")] static extern bool IsWindow(IntPtr h); [DllImport("user32.dll")] static extern uint GetWindowThreadProcessId(IntPtr h, out uint pid); [DllImport("user32.dll", EntryPoint = "GetWindowLong")] static extern int GetWindowLong32(IntPtr h, int idx); [DllImport("user32.dll", EntryPoint = "GetWindowLongPtr")] static extern IntPtr GetWindowLongPtr64(IntPtr h, int idx); [DllImport("user32.dll")] static extern bool SetWindowPos(IntPtr h, IntPtr insertAfter, int x, int y, int cx, int cy, uint flags); static IntPtr GetExStyle(IntPtr h) { if (IntPtr.Size == 8) return GetWindowLongPtr64(h, GWL_EXSTYLE); return new IntPtr(GetWindowLong32(h, GWL_EXSTYLE)); } public static bool IsTopMost(IntPtr h) { if (h == IntPtr.Zero || !IsWindow(h)) return false; long st = GetExStyle(h).ToInt64(); return (st & WS_EX_TOPMOST) != 0; } public static bool SetTop(IntPtr h, bool on) { if (h == IntPtr.Zero || !IsWindow(h)) return false; return SetWindowPos(h, on ? HWND_TOPMOST : HWND_NOTOPMOST, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE); } public static string ReadTitle(IntPtr h) { int len = GetWindowTextLength(h); if (len <= 0) return ""; StringBuilder sb = new StringBuilder(len + 2); int got = GetWindowText(h, sb, sb.Capacity); if (got <= 0) return ""; return sb.ToString().Trim(); } // 这些是系统壳层/输入法留下的隐形窗口,列出来只会让人困惑 static readonly string[] JunkTitles = new string[] { "Program Manager", "Default IME", "MSCTFIME UI", "Windows 输入体验", "Windows Input Experience", "Microsoft Text Input Application" }; public static bool IsJunkTitle(string title) { if (title == null) return true; string t = title.Trim(); if (t.Length == 0) return true; for (int i = 0; i < JunkTitles.Length; i++) if (string.Equals(t, JunkTitles[i], StringComparison.OrdinalIgnoreCase)) return true; return false; } public static string ProcessNameOf(IntPtr h) { uint pid; GetWindowThreadProcessId(h, out pid); if (pid == 0) return ""; try { return Process.GetProcessById((int)pid).ProcessName; } catch { return ""; } } // excludeOwner:本程序自己的窗口,不该出现在列表里 public static List Scan(IntPtr excludeOwner) { List list = new List(); EnumWindows(delegate(IntPtr h, IntPtr p) { if (!IsWindowVisible(h)) return true; if (h == excludeOwner) return true; string title = ReadTitle(h); if (IsJunkTitle(title)) return true; WinItem w = new WinItem(); w.Handle = h; w.Title = title; w.Process = ProcessNameOf(h); w.TopMost = IsTopMost(h); list.Add(w); return true; }, IntPtr.Zero); list.Sort(delegate(WinItem a, WinItem b) { if (a.TopMost != b.TopMost) return a.TopMost ? -1 : 1; return string.Compare(a.Title, b.Title, StringComparison.CurrentCulture); }); return list; } public static string ShortTitle(string t, int max) { if (t == null) return ""; if (t.Length <= max) return t; return t.Substring(0, max - 1) + "…"; } } // 置顶规则:进程名 + 完整标题。标题变了就不再自动套用,避免误伤同名窗口 public class PinStore { readonly string _file; List _keys = new List(); public PinStore(string file) { _file = file; } public int Count { get { return _keys.Count; } } public bool Contains(WinItem w) { string k = w.Key; for (int i = 0; i < _keys.Count; i++) if (string.Equals(_keys[i], k, StringComparison.OrdinalIgnoreCase)) return true; return false; } public bool Add(WinItem w) { if (w == null || string.IsNullOrEmpty(w.Title)) return false; if (Contains(w)) return false; _keys.Add(w.Key); return true; } public bool Remove(WinItem w) { string k = w.Key; for (int i = _keys.Count - 1; i >= 0; i--) { if (string.Equals(_keys[i], k, StringComparison.OrdinalIgnoreCase)) { _keys.RemoveAt(i); return true; } } return false; } public void Clear() { _keys.Clear(); } public void Save() { StringBuilder sb = new StringBuilder(); for (int i = 0; i < _keys.Count; i++) sb.AppendLine(_keys[i]); File.WriteAllText(_file, sb.ToString(), new UTF8Encoding(false)); } public void Load() { _keys = new List(); if (!File.Exists(_file)) return; string[] lines = File.ReadAllLines(_file, Encoding.UTF8); for (int i = 0; i < lines.Length; i++) { string s = lines[i].Trim(); if (s.Length == 0) continue; if (s.IndexOf('|') <= 0) continue; if (!_keys.Contains(s)) _keys.Add(s); } } // 打开时把规则套到当前窗口上,返回实际置顶了几个 public int ApplyTo(List wins) { int n = 0; for (int i = 0; i < wins.Count; i++) { if (wins[i].TopMost) continue; if (!Contains(wins[i])) continue; if (TopMostOps.SetTop(wins[i].Handle, true)) { wins[i].TopMost = true; n++; } } return n; } } public class TopMostForm : Form { ListView _list; Label _status; CheckBox _remember; Timer _tick; PinStore _store; bool _filling; public TopMostForm() { Text = "窗口置顶助手 - 绿色工具箱"; ClientSize = new Size(760, 520); MinimumSize = new Size(620, 420); StartPosition = FormStartPosition.CenterScreen; Font = new Font("Microsoft YaHei UI", 9F); string dir = Path.Combine(Path.GetDirectoryName(Application.ExecutablePath), "置顶规则"); _store = new PinStore(Path.Combine(dir, "pins.txt")); Label tip = new Label(); tip.Text = "勾选任意窗口即可让它永远浮在最上层(看文档、抄数据、盯监控时很好用)。取消勾选即恢复。"; tip.AutoSize = false; tip.Dock = DockStyle.Top; tip.Height = 36; tip.Padding = new Padding(10, 10, 10, 0); tip.ForeColor = Color.FromArgb(70, 70, 70); Controls.Add(tip); Panel bar = new Panel(); bar.Dock = DockStyle.Top; bar.Height = 44; bar.Padding = new Padding(10, 6, 10, 6); Button refresh = new Button(); refresh.Text = "刷新列表"; refresh.SetBounds(10, 8, 88, 28); refresh.Click += delegate { Fill(); }; bar.Controls.Add(refresh); Button reset = new Button(); reset.Text = "全部取消置顶"; reset.SetBounds(106, 8, 116, 28); reset.Click += delegate { ClearAll(); }; bar.Controls.Add(reset); _remember = new CheckBox(); _remember.Text = "记住这些窗口,下次打开自动恢复"; _remember.SetBounds(240, 11, 240, 22); _remember.CheckedChanged += delegate { SaveRules(); }; bar.Controls.Add(_remember); Label hint = new Label(); hint.Text = "提示:置顶的窗口会盖住本窗口,先勾完再关我"; hint.AutoSize = false; hint.SetBounds(490, 13, 260, 20); hint.ForeColor = Color.FromArgb(140, 140, 140); bar.Controls.Add(hint); Controls.Add(bar); _list = new ListView(); _list.Dock = DockStyle.Fill; _list.View = View.Details; _list.CheckBoxes = true; _list.FullRowSelect = true; _list.GridLines = false; _list.HideSelection = false; _list.Columns.Add("窗口标题", 430); _list.Columns.Add("程序", 150); _list.Columns.Add("状态", 100); _list.ItemCheck += OnItemCheck; Controls.Add(_list); Panel bottom = new Panel(); bottom.Dock = DockStyle.Bottom; bottom.Height = 32; _status = new Label(); _status.Dock = DockStyle.Fill; _status.TextAlign = ContentAlignment.MiddleLeft; _status.Padding = new Padding(12, 0, 0, 0); _status.ForeColor = Color.FromArgb(100, 100, 100); bottom.Controls.Add(_status); Controls.Add(bottom); Load += delegate { _store.Load(); _remember.Checked = _store.Count > 0; Fill(); int n = _store.ApplyTo(Current()); if (n > 0) { _status.Text = "已按记忆恢复 " + n + " 个窗口的置顶状态"; Fill(); } }; // 5 秒轻刷一次,只更新标题变化和已关闭的窗口;不打断正在进行的操作 _tick = new Timer(); _tick.Interval = 5000; _tick.Tick += delegate { if (_filling) return; if (_list.Focused) return; Fill(); }; // 停靠布局按 z-order 逆序计算:主列表必须最先布局,否则被顶部两行盖住第一屏 Controls.SetChildIndex(_list, 0); Controls.SetChildIndex(bottom, 1); Controls.SetChildIndex(tip, 2); Controls.SetChildIndex(bar, 3); _tick.Start(); } List _cache = new List(); List Current() { return _cache; } void Fill() { if (_filling) return; _filling = true; try { int keepTop = _list.TopItem == null ? 0 : _list.TopItem.Index; _cache = TopMostOps.Scan(Handle); _list.BeginUpdate(); _list.Items.Clear(); for (int i = 0; i < _cache.Count; i++) { WinItem w = _cache[i]; ListViewItem it = new ListViewItem(TopMostOps.ShortTitle(w.Title, 70)); it.SubItems.Add(w.Process); it.SubItems.Add(w.TopMost ? "已置顶" : ""); it.Tag = w; it.Checked = w.TopMost; if (w.TopMost) it.ForeColor = Color.FromArgb(0, 120, 60); _list.Items.Add(it); } _list.EndUpdate(); _status.Text = "共 " + _cache.Count + " 个可见窗口" + (_remember.Checked ? ",已启用记忆" : ""); } finally { _filling = false; } } void OnItemCheck(object sender, ItemCheckEventArgs e) { if (_filling) return; WinItem w = _list.Items[e.Index].Tag as WinItem; if (w == null) return; bool want = e.NewValue == CheckState.Checked; if (!TopMostOps.SetTop(w.Handle, want)) { _status.Text = "操作失败:这个窗口可能已经关闭了"; e.NewValue = want ? CheckState.Unchecked : CheckState.Checked; return; } w.TopMost = want; _list.Items[e.Index].SubItems[2].Text = want ? "已置顶" : ""; _list.Items[e.Index].ForeColor = want ? Color.FromArgb(0, 120, 60) : Color.Black; if (_remember.Checked) { if (want) _store.Add(w); else _store.Remove(w); _store.Save(); } _status.Text = want ? ("已置顶:" + TopMostOps.ShortTitle(w.Title, 40)) : ("已取消置顶:" + TopMostOps.ShortTitle(w.Title, 40)); } void ClearAll() { int n = 0; for (int i = 0; i < _cache.Count; i++) if (_cache[i].TopMost && TopMostOps.SetTop(_cache[i].Handle, false)) n++; _store.Clear(); _store.Save(); Fill(); _status.Text = "已取消 " + n + " 个窗口的置顶"; } void SaveRules() { if (_remember.Checked) { // 打开记忆时,把当前已置顶的全记下来 for (int i = 0; i < _cache.Count; i++) if (_cache[i].TopMost) _store.Add(_cache[i]); } else { _store.Clear(); } try { _store.Save(); } catch (Exception ex) { _status.Text = "规则保存失败:" + ex.Message; } } } public static class TopMostSelfTest { 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-pin-" + Guid.NewGuid().ToString("N").Substring(0, 8)) : dir; Form probe = null; try { Directory.CreateDirectory(baseDir); // 标题过滤 Check("空标题算垃圾", TopMostOps.IsJunkTitle(""), true); Check("空格标题算垃圾", TopMostOps.IsJunkTitle(" "), true); Check("Program Manager 剔除", TopMostOps.IsJunkTitle("Program Manager"), true); Check("Default IME 剔除", TopMostOps.IsJunkTitle("Default IME"), true); Check("正常标题保留", TopMostOps.IsJunkTitle("记事本 - 无标题"), false); Check("null 标题算垃圾", TopMostOps.IsJunkTitle(null), true); Check("短标题不截断", TopMostOps.ShortTitle("abc", 10), "abc"); Check("长标题截断带省略号", TopMostOps.ShortTitle("abcdefghijk", 5), "abcd…"); Check("刚好等长不截", TopMostOps.ShortTitle("abcde", 5), "abcde"); // 造一个真实窗口来验证枚举与置顶 string tag = "GT-PIN-TEST-" + Guid.NewGuid().ToString("N").Substring(0, 6); probe = new Form(); probe.Text = tag; probe.StartPosition = FormStartPosition.Manual; probe.SetBounds(-4000, -4000, 200, 120); // 挪到屏幕外,别弹到用户脸上 probe.ShowInTaskbar = false; probe.Show(); Application.DoEvents(); List wins = TopMostOps.Scan(IntPtr.Zero); WinItem mine = null; for (int i = 0; i < wins.Count; i++) if (wins[i].Title == tag) { mine = wins[i]; break; } Check("枚举能找到自建窗口", mine != null, true); if (mine != null) { Check("新窗口默认不置顶", mine.TopMost, false); Check("置顶返回成功", TopMostOps.SetTop(mine.Handle, true), true); Check("置顶后状态为真", TopMostOps.IsTopMost(mine.Handle), true); Check("取消置顶返回成功", TopMostOps.SetTop(mine.Handle, false), true); Check("取消后状态为假", TopMostOps.IsTopMost(mine.Handle), false); Check("非法句柄置顶返回假", TopMostOps.SetTop(IntPtr.Zero, true), false); Check("非法句柄查状态为假", TopMostOps.IsTopMost(new IntPtr(12345)), false); Check("进程名非空", mine.Process.Length > 0, true); } // 排除自身窗口 List noSelf = TopMostOps.Scan(probe.Handle); bool hasSelf = false; for (int i = 0; i < noSelf.Count; i++) if (noSelf[i].Title == tag) hasSelf = true; Check("排除句柄后看不到自己", hasSelf, false); // 规则存储 string ruleFile = Path.Combine(baseDir, "pins.txt"); PinStore st = new PinStore(ruleFile); WinItem w1 = new WinItem(); w1.Handle = new IntPtr(1); w1.Process = "notepad"; w1.Title = "草稿.txt - 记事本"; WinItem w2 = new WinItem(); w2.Handle = new IntPtr(2); w2.Process = "chrome"; w2.Title = "工作台"; WinItem w3 = new WinItem(); w3.Handle = new IntPtr(3); w3.Process = "notepad"; w3.Title = "草稿.txt - 记事本"; Check("空规则数量 0", st.Count, 0); Check("加入第一条", st.Add(w1), true); Check("重复加入返回假", st.Add(w3), false); Check("数量仍为 1", st.Count, 1); Check("同进程同标题算命中", st.Contains(w3), true); Check("不同标题不命中", st.Contains(w2), false); st.Add(w2); Check("两条规则", st.Count, 2); st.Save(); Check("规则文件已生成", File.Exists(ruleFile), true); PinStore st2 = new PinStore(ruleFile); st2.Load(); Check("重新读取规则数", st2.Count, 2); Check("读回后命中记事本", st2.Contains(w1), true); Check("读回后命中浏览器", st2.Contains(w2), true); File.WriteAllText(ruleFile, "坏行没有分隔符\r\n\r\nnotepad|草稿.txt - 记事本\r\n", new UTF8Encoding(false)); PinStore st3 = new PinStore(ruleFile); st3.Load(); Check("坏行被跳过", st3.Count, 1); Check("删除规则返回真", st3.Remove(w1), true); Check("删除后数量 0", st3.Count, 0); Check("重复删除返回假", st3.Remove(w1), false); st3.Add(w2); st3.Clear(); Check("清空后数量 0", st3.Count, 0); // ApplyTo:只对匹配且未置顶的动手(用假句柄,SetTop 会失败,返回 0) PinStore st4 = new PinStore(Path.Combine(baseDir, "p2.txt")); st4.Add(w2); List fake = new List(); WinItem f1 = new WinItem(); f1.Handle = IntPtr.Zero; f1.Process = "chrome"; f1.Title = "工作台"; fake.Add(f1); Check("假句柄套用规则不会误置顶", st4.ApplyTo(fake), 0); // 标题拼接 Check("Key 格式", w1.Key, "notepad|草稿.txt - 记事本"); } catch (Exception ex) { _fail++; _lines.Add(" [!!] 自测中途异常:" + ex.GetType().Name + " " + ex.Message); } finally { try { if (probe != null) { probe.Close(); probe.Dispose(); } } catch { } 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-topmost.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(TopMostSelfTest.Run(args.Length >= 2 ? args[1] : null)); } Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new TopMostForm()); } } }