// ===================================================================================== // SettingsComboBoxTests —— 设置页悬浮条「进程/类名/标题」下拉的原生选择回归。 // // 覆盖范围:用真实的 Win32 消息(鼠标点击列表项 + 关闭下拉、方向键选择)驱动下拉, // 断言 CBN_SELENDOK/SELCHANGE/CLOSEUP 之后原生 EDIT 文本与 ComboBox.Text 一致, // 并且刷新建议列表 / 切换悬浮条 / 手动输入后选值仍然保留;最后 Save+Load 校验持久化。 // // 为什么这样测:这是 WinForms 自身控件与其 Win32 子窗口(Edit/List)之间的同步问题, // 只能靠真实的消息循环验证;用例运行在 Program.Main 的 STA 线程上,所有 HWND 消息 // 只发给本用例自己创建的控件,不涉及 UIA、真实目标窗口枚举、SendInput 或杀进程。 // 截图仅在设置了 PACS_REGRESSION_SCREENSHOTS 环境变量时写出(失败时也有留存)。 // // 新增用例:加到 Register(...) 列表并实现 private static void 方法,断言走 Check.*; // 私有成员通过反射访问(Field/PrivateCombo/InvokePrivate)。 // ===================================================================================== using System; using System.Collections.Generic; using System.Drawing; using System.IO; using System.Reflection; using System.Runtime.InteropServices; using System.Text; using System.Threading; using System.Windows.Forms; using pacs_win_uia.Models; using pacs_win_uia.Services; using pacs_win_uia.UI; namespace PacsWinUia.RegressionTests { // Runs on Program.Main's STA thread. All HWND messages address this test's controls only. // No UIA, user settings, target enumeration, SendInput or process termination is involved. internal static class SettingsComboBoxTests { public static void Register(IList> tests) { // 防:原生选择后 ComboBox.Text 与 EDIT 文本不同步(经典“显示回退成上一个值”)、 // 刷新或手动输入丢值、以及保存后进程/类名/标题未持久化。 tests.Add(new KeyValuePair( "Floating suggestions native mouse/keyboard selection, refresh and persistence", SelectionRefreshAndPersistence)); } private static void SelectionRefreshAndPersistence() { Check.Equal(ApartmentState.STA, Thread.CurrentThread.GetApartmentState(), "WinForms requires STA"); using (var temporary = new TemporaryDirectory()) { var settings = AppSettings.CreateDefault(); settings.FloatingButton.Bars = new List { new FloatingBarDefinition { Name = "Selection test", Enabled = false }, new FloatingBarDefinition { Name = "Manual input test", Enabled = false, ProcessName = "other.exe", WindowClass = "OtherClass", WindowTitleKeyword = "Other title" } }; var store = new AppSettingsStore(temporary.File("preferred.json"), temporary.File("fallback.json")); using (var form = new SettingsForm(settings, store, null)) { // OnLoad normally enumerates real windows asynchronously. Disable that in this // isolated fixture and supply deterministic snapshots instead; never call Load(). Field("_refreshingSuggestions").SetValue(form, true); form.Show(); foreach (Control control in form.Controls) if (control is TabControl) ((TabControl)control).SelectedIndex = 2; Application.DoEvents(); ComboBox process = PrivateCombo(form, "_barProcess"); ComboBox windowClass = PrivateCombo(form, "_barClass"); ComboBox title = PrivateCombo(form, "_barTitle"); SetSuggestions(form, Window(1, "fixture.exe", "ClassA", "Window A"), Window(2, "fixture.exe", "ClassB", "Window B"), Window(3, "second.exe", "SecondClass", "Second window")); InvokePrivate(form, "RebuildWindowSuggestions", true); Check.Equal(3, process.Items.Count, "Multiple process suggestions"); NativeMouseSelect(process, 1, "fixture.exe", form); NativeMouseSelect(windowClass, 0, "ClassA", form); NativeMouseSelect(title, 1, "Window B", form); NativeKeyboardSelect(windowClass, "ClassB", form); // Both selection methods must leave the native EDIT and managed Text identical. AssertText(process, "fixture.exe", "process retained"); AssertText(windowClass, "ClassB", "class retained"); AssertText(title, "Window B", "title retained"); InvokePrivate(form, "RebuildWindowSuggestions", true); AssertText(process, "fixture.exe", "selected process after refresh"); AssertText(windowClass, "ClassB", "selected class after refresh"); AssertText(title, "Window B", "selected title after refresh"); var bars = (ListBox)Field("_barList").GetValue(form); bars.SelectedIndex = 1; AssertText(process, "other.exe", "switch bar process"); process.Text = "manual.exe"; windowClass.Text = "ManualClass"; title.Text = "Manual title"; title.Select(2, 4); InvokePrivate(form, "RebuildWindowSuggestions", true); AssertText(process, "manual.exe", "manual process after refresh"); AssertText(windowClass, "ManualClass", "manual class after refresh"); AssertText(title, "Manual title", "manual title after refresh"); bars.SelectedIndex = 0; AssertText(process, "fixture.exe", "switch back process"); AssertText(windowClass, "ClassB", "switch back class"); AssertText(title, "Window B", "switch back title"); SaveScreenshot(form, "selected-values"); InvokePrivate(form, "Save"); } AppSettings reloaded = store.Load(); AssertBar(reloaded.FloatingButton.Bars[0], "fixture.exe", "ClassB", "Window B"); AssertBar(reloaded.FloatingButton.Bars[1], "manual.exe", "ManualClass", "Manual title"); } } private static void AssertBar(FloatingBarDefinition bar, string process, string windowClass, string title) { Check.Equal(process, bar.ProcessName, "Saved process"); Check.Equal(windowClass, bar.WindowClass, "Saved class"); Check.Equal(title, bar.WindowTitleKeyword, "Saved title"); } private static NativeWindowInfo Window(int handle, string process, string windowClass, string title) { return new NativeWindowInfo(new IntPtr(handle)) { ProcessId = handle + 100, ProcessName = process, ClassName = windowClass, Title = title, IsVisible = true }; } private static void NativeMouseSelect(ComboBox box, int index, string expected, SettingsForm form) { int commits = 0, closes = 0; EventHandler committed = delegate { commits++; }; EventHandler closed = delegate { closes++; }; box.SelectionChangeCommitted += committed; box.DropDownClosed += closed; try { box.Focus(); box.DroppedDown = true; Application.DoEvents(); ComboInfo info = GetInfo(box); var rect = new NativeRect(); SendMessageRect(info.List, 0x198 /* LB_GETITEMRECT */, new IntPtr(index), ref rect); IntPtr point = new IntPtr(((rect.Top + (rect.Bottom - rect.Top) / 2) << 16) | 20); // Actual list-window input: native code generates CBN_SELENDOK/SELCHANGE/CLOSEUP. SendMessage(info.List, 0x200 /* WM_MOUSEMOVE */, IntPtr.Zero, point); SendMessage(info.List, 0x201 /* WM_LBUTTONDOWN */, new IntPtr(1), point); SendMessage(info.List, 0x202 /* WM_LBUTTONUP */, IntPtr.Zero, point); Check.True(commits > 0, "Native mouse did not commit selection"); Check.True(closes > 0, "Native mouse did not close dropdown"); VerifySettled(box, expected, form, "mouse"); } finally { box.SelectionChangeCommitted -= committed; box.DropDownClosed -= closed; } } private static void NativeKeyboardSelect(ComboBox box, string expected, SettingsForm form) { int changes = 0; EventHandler changed = delegate { changes++; }; box.SelectedIndexChanged += changed; try { box.Focus(); // Native arrow-key selection with the list closed (also used by keyboard-only users). SendMessage(box.Handle, 0x100 /* WM_KEYDOWN */, new IntPtr((int)Keys.Down), IntPtr.Zero); SendMessage(box.Handle, 0x101 /* WM_KEYUP */, new IntPtr((int)Keys.Down), IntPtr.Zero); Check.True(changes > 0, "Native keyboard did not select an item"); VerifySettled(box, expected, form, "keyboard"); } finally { box.SelectedIndexChanged -= changed; } } private static void VerifySettled(ComboBox box, string expected, SettingsForm form, string phase) { try { AssertText(box, expected, phase + " immediately after native close/selection"); Application.DoEvents(); AssertText(box, expected, phase + " after DoEvents"); ((Control)Field("_barName").GetValue(form)).Focus(); Application.DoEvents(); AssertText(box, expected, phase + " after focus loss"); } catch { SaveScreenshot(form, "failure-" + phase); throw; } } private static void AssertText(ComboBox box, string expected, string phase) { var text = new StringBuilder(4096); GetWindowText(GetInfo(box).Edit, text, text.Capacity); Check.Equal(expected, text.ToString(), phase + ": native EDIT text"); Check.Equal(expected, box.Text, phase + ": ComboBox.Text"); } private static void SaveScreenshot(Form form, string name) { string directory = Environment.GetEnvironmentVariable("PACS_REGRESSION_SCREENSHOTS"); if (string.IsNullOrEmpty(directory)) return; Directory.CreateDirectory(directory); using (var bitmap = new Bitmap(form.Width, form.Height)) { form.DrawToBitmap(bitmap, new Rectangle(Point.Empty, bitmap.Size)); string file = Path.Combine(directory, name + ".png"); bitmap.Save(file, System.Drawing.Imaging.ImageFormat.Png); Console.WriteLine("Screenshot: " + file); } } private static FieldInfo Field(string name) { return typeof(SettingsForm).GetField(name, BindingFlags.Instance | BindingFlags.NonPublic); } private static ComboBox PrivateCombo(SettingsForm form, string field) { return (ComboBox)Field(field).GetValue(form); } private static void SetSuggestions(SettingsForm form, params NativeWindowInfo[] windows) { Field("_suggestedWindows").SetValue(form, new List(windows)); } private static void InvokePrivate(SettingsForm form, string method, params object[] arguments) { typeof(SettingsForm).GetMethod(method, BindingFlags.Instance | BindingFlags.NonPublic).Invoke(form, arguments); } private static ComboInfo GetInfo(ComboBox box) { var info = new ComboInfo { Size = Marshal.SizeOf(typeof(ComboInfo)) }; Check.True(GetComboBoxInfo(box.Handle, ref info), "GetComboBoxInfo failed"); return info; } [StructLayout(LayoutKind.Sequential)] private struct NativeRect { public int Left, Top, Right, Bottom; } [StructLayout(LayoutKind.Sequential)] private struct ComboInfo { public int Size; public NativeRect ItemRect, ButtonRect; public int ButtonState; public IntPtr Combo, Edit, List; } [DllImport("user32.dll")] private static extern bool GetComboBoxInfo(IntPtr handle, ref ComboInfo info); [DllImport("user32.dll", CharSet = CharSet.Unicode)] private static extern int GetWindowText(IntPtr handle, StringBuilder text, int length); [DllImport("user32.dll", CharSet = CharSet.Unicode)] private static extern IntPtr SendMessage(IntPtr handle, int message, IntPtr wParam, IntPtr lParam); [DllImport("user32.dll", EntryPoint = "SendMessageW")] private static extern IntPtr SendMessageRect(IntPtr handle, int message, IntPtr wParam, ref NativeRect rect); } }