diff --git a/docs/XPath定位.md b/docs/XPath定位.md index cdf6d57..6f7bdf3 100644 --- a/docs/XPath定位.md +++ b/docs/XPath定位.md @@ -397,6 +397,8 @@ i3/o1 点击“检测显示条件”,按提示处理: +> 检测是在设置页里做的,而设置窗口本身会盖住目标窗口。因此**检测会忽略本工具自己的窗口**(主界面、设置窗口),只报告外部程序的遮挡;运行时仍然会严格判断——设置窗口关掉后,悬浮条才会按条件出现。 + 1. 悬浮条是否启用; 2. 是否有至少一个启用按钮; 3. 是否填写了窗口条件; diff --git a/src/pacs_win_uia/Services/FloatingBarManager.cs b/src/pacs_win_uia/Services/FloatingBarManager.cs index 4ba555d..9404fa3 100644 --- a/src/pacs_win_uia/Services/FloatingBarManager.cs +++ b/src/pacs_win_uia/Services/FloatingBarManager.cs @@ -422,13 +422,30 @@ namespace pacs_win_uia.Services /// Run on a worker thread. Never activates windows, invokes buttons or runs commands. public static FloatingBarDisplayCheck CheckDisplayConditions(FloatingBarDefinition bar) + { + return CheckDisplayConditions(bar, false); + } + + /// + /// True for the settings-page diagnostic: the tool's own windows (main window, this settings + /// dialog) are not counted as occluders. While the dialog is open it covers the target, so a + /// strict check would always report "被遮挡" and tell the operator nothing. Runtime keeps false. + /// + public static FloatingBarDisplayCheck CheckDisplayConditions(FloatingBarDefinition bar, + bool ignoreOwnProcessWindows) { IList windows = null; - return EvaluateDisplay(bar, ref windows); + return EvaluateDisplay(bar, ref windows, ignoreOwnProcessWindows); } private static FloatingBarDisplayCheck EvaluateDisplay(FloatingBarDefinition bar, ref IList windows) + { + return EvaluateDisplay(bar, ref windows, false); + } + + private static FloatingBarDisplayCheck EvaluateDisplay(FloatingBarDefinition bar, + ref IList windows, bool ignoreOwnProcessWindows) { var result = new FloatingBarDisplayCheck(); try @@ -472,10 +489,10 @@ namespace pacs_win_uia.Services result.Anchor = window.Handle; result.Details = "锚定窗口:" + window + ";PID=" + window.ProcessId; if (bar.RequireWindowVisible && !WindowVisibility.IsVisibleOnScreen(window.Handle, - window.WindowRectangle, System.Diagnostics.Process.GetCurrentProcess().Id, out error)) + window.WindowRectangle, System.Diagnostics.Process.GetCurrentProcess().Id, + ignoreOwnProcessWindows, out error)) { - result.Reason = "锚定窗口可见性不满足:" + error - + " 设置窗口本身也可能遮挡目标;请移开设置窗口后重新检测。"; + result.Reason = "锚定窗口可见性不满足:" + error; return result; } if (condition != null) diff --git a/src/pacs_win_uia/Services/WindowVisibility.cs b/src/pacs_win_uia/Services/WindowVisibility.cs index 8fab514..7e4311f 100644 --- a/src/pacs_win_uia/Services/WindowVisibility.cs +++ b/src/pacs_win_uia/Services/WindowVisibility.cs @@ -31,6 +31,23 @@ namespace pacs_win_uia.Services /// public static bool TryGetVisibleRegion(IntPtr targetWindow, bool requireForeground, IEnumerable ignoredOverlayWindows, out Region visibleRegion, out string reason) + { + return TryGetVisibleRegion(targetWindow, requireForeground, ignoredOverlayWindows, false, null, + out visibleRegion, out reason); + } + + /// + /// Diagnostic mode: windows of this process (MainForm/SettingsForm) are not counted as + /// occluders. The settings dialog itself covers the target while the operator is configuring, + /// so a strict check would always report "occluded" and teach nothing. Runtime callers keep + /// passing false. + /// + /// + /// Optional: receives the windows that actually removed visible area, in Z order. + /// + public static bool TryGetVisibleRegion(IntPtr targetWindow, bool requireForeground, + IEnumerable ignoredOverlayWindows, bool ignoreOwnProcessWindows, + IList occludingWindows, out Region visibleRegion, out string reason) { visibleRegion = null; reason = null; @@ -75,11 +92,27 @@ namespace pacs_win_uia.Services reachedTarget = true; return false; } - if (!ignored.Contains(window) && !IsToolOverlay(window) && IsDrawable(window)) + bool skip = ignored.Contains(window) || IsToolOverlay(window) || + (ignoreOwnProcessWindows && IsOwnProcessWindow(window)); + if (!skip && IsDrawable(window)) { using (Region obstruction = CreateWindowRegion(window)) { - if (obstruction != null) result.Exclude(obstruction); + if (obstruction != null) + { + bool removes = false; + using (Region overlap = result.Clone()) + { + overlap.Intersect(obstruction); + removes = HasArea(overlap); + } + + if (removes) + { + result.Exclude(obstruction); + if (occludingWindows != null) occludingWindows.Add(window); + } + } } } return true; @@ -89,7 +122,9 @@ namespace pacs_win_uia.Services if (!reachedTarget || !IsDrawable(target) || (requireForeground && !IsForegroundWindow(target)) || !HasArea(result)) { - reason = "目标不在前台、已隐藏或可见区域被完全遮挡。"; + reason = "目标不在前台、已隐藏或可见区域被完全遮挡。" + + (DescribeOccluders(occludingWindows, System.Diagnostics.Process.GetCurrentProcess().Id, + ignoreOwnProcessWindows) ?? string.Empty); return false; } visibleRegion = result; @@ -129,6 +164,61 @@ namespace pacs_win_uia.Services } } + /// True for windows of this process (main window, settings dialog, own overlays). + public static bool IsOwnProcessWindow(IntPtr window) + { + if (window == IntPtr.Zero) return false; + uint processId; + NativeMethods.GetWindowThreadProcessId(window, out processId); + return unchecked((int)processId) == System.Diagnostics.Process.GetCurrentProcess().Id; + } + + /// + /// Names the windows that hide the target, so "被遮挡" says by what. Chinese labels because this + /// text is shown in the settings dialog. + /// + public static string DescribeOccluders(IList occludingWindows, int ownProcessId, + bool ignoredOwnProcessWindows) + { + if (occludingWindows == null || occludingWindows.Count == 0) return null; + int own = 0; + var names = new List(); + foreach (IntPtr handle in occludingWindows) + { + if (handle == IntPtr.Zero || !NativeMethods.IsWindow(handle)) continue; + uint processId; + NativeMethods.GetWindowThreadProcessId(handle, out processId); + bool isOwn = unchecked((int)processId) == ownProcessId; + if (isOwn) own++; + if (names.Count < 4) + { + var className = new System.Text.StringBuilder(128); + NativeMethods.GetClassName(handle, className, className.Capacity); + names.Add((isOwn ? "【本工具】" : string.Empty) + className + + " " + NativeWindowInfoFormat(handle) + " PID " + unchecked((int)processId)); + } + } + + string list = names.Count == 0 ? "(无法读取遮挡窗口信息)" : string.Join(";", names.ToArray()); + if (own == occludingWindows.Count) + { + return "遮挡者全部是本工具自己的窗口(主界面/设置窗口):" + list + + "。这是设置页自检时的正常现象,把本工具窗口移开、或保存后关闭设置窗口,悬浮条即会按条件显示。"; + } + + if (own > 0) + { + return "遮挡窗口:" + list + "(其中 " + own + " 个是本工具窗口)。请移开这些窗口后重新检测。"; + } + + return "遮挡窗口:" + list + "。请把目标窗口切到前面后重新检测。"; + } + + private static string NativeWindowInfoFormat(IntPtr handle) + { + return "0x" + handle.ToInt64().ToString("X"); + } + private static Region CreateWindowRegion(IntPtr window) { NativeMethods.RECT bounds; @@ -171,6 +261,16 @@ namespace pacs_win_uia.Services /// public static bool IsVisibleOnScreen(IntPtr topLevelWindow, Rectangle rect, int ownProcessId, out string reason) + { + return IsVisibleOnScreen(topLevelWindow, rect, ownProcessId, false, out reason); + } + + /// + /// Diagnostic mode only (see TryGetVisibleRegion): the tool's own windows do not count as + /// occluders, so the settings page can still explain what would happen at runtime. + /// + public static bool IsVisibleOnScreen(IntPtr topLevelWindow, Rectangle rect, + int ownProcessId, bool ignoreOwnProcessWindows, out string reason) { reason = null; if (rect.Width <= 1 || rect.Height <= 1 || !SystemInformation.VirtualScreen.IntersectsWith(rect)) @@ -180,7 +280,9 @@ namespace pacs_win_uia.Services } if (topLevelWindow == IntPtr.Zero) return true; Region visible; - if (!TryGetVisibleRegion(topLevelWindow, false, null, out visible, out reason)) return false; + var occluders = new List(); + if (!TryGetVisibleRegion(topLevelWindow, false, null, ignoreOwnProcessWindows, occluders, + out visible, out reason)) return false; using (visible) using (Region missing = CreateWindowRegion(GetRoot(topLevelWindow))) { @@ -204,7 +306,8 @@ namespace pacs_win_uia.Services } missing.Exclude(visible); if (!HasArea(missing)) return true; - reason = "该区域部分或全部被其他窗口遮挡。"; + reason = "该区域部分或全部被其他窗口遮挡。" + + (DescribeOccluders(occluders, ownProcessId, ignoreOwnProcessWindows) ?? string.Empty); return false; } } diff --git a/src/pacs_win_uia/UI/SettingsForm.cs b/src/pacs_win_uia/UI/SettingsForm.cs index 0e2b703..877f8d6 100644 --- a/src/pacs_win_uia/UI/SettingsForm.cs +++ b/src/pacs_win_uia/UI/SettingsForm.cs @@ -719,7 +719,7 @@ namespace pacs_win_uia.UI private sealed class WindowSuggestion { internal NativeWindowInfo Window; - internal string Value; + public string Value { get; set; } public override string ToString() { return Value + " — " + (string.IsNullOrEmpty(Window.Title) ? "(无标题)" : Window.Title) @@ -735,7 +735,23 @@ namespace pacs_win_uia.UI var box = new ComboBox { Width = width, DropDownStyle = ComboBoxStyle.DropDown, - DropDownWidth = 780, IntegralHeight = false, MaxDropDownItems = 14 + DropDownWidth = 780, IntegralHeight = false, MaxDropDownItems = 14, + DisplayMember = "Value", ValueMember = "Value", DrawMode = DrawMode.OwnerDrawFixed + }; + // Native selection copies DisplayMember into the EDIT *after* SelectionChangeCommitted. + // Keep that text raw and draw the richer description only in the drop-down list. Clearing + // SelectedIndex during commit makes the native CBN_SELCHANGE overwrite the EDIT with "". + box.DrawItem += delegate(object sender, DrawItemEventArgs e) + { + e.DrawBackground(); + if (e.Index >= 0 && e.Index < box.Items.Count) + { + var item = (WindowSuggestion)box.Items[e.Index]; + string display = (e.State & DrawItemState.ComboBoxEdit) != 0 ? item.Value : item.ToString(); + TextRenderer.DrawText(e.Graphics, display, e.Font, e.Bounds, e.ForeColor, + TextFormatFlags.Left | TextFormatFlags.VerticalCenter | TextFormatFlags.NoPrefix); + } + e.DrawFocusRectangle(); }; box.TextChanged += delegate { @@ -744,21 +760,22 @@ namespace pacs_win_uia.UI }; box.SelectionChangeCommitted += delegate { + if (_suppressBarEvents) return; var suggestion = box.SelectedItem as WindowSuggestion; if (suggestion == null) return; - _suppressBarEvents = true; - try + + // Preserve the native selection until WinForms finishes CBN_SELCHANGE/CLOSEUP. + // DisplayMember already ensures the editor receives the actual value. + box.Text = suggestion.Value; + // A choice supplies useful defaults only for blank fields. Typed conditions win. + if (field == 0) { - box.SelectedIndex = -1; - box.Text = suggestion.Value; - // A choice supplies useful defaults only for blank fields. Typed conditions win. - if (field == 0) - { - if (string.IsNullOrWhiteSpace(_barClass.Text)) _barClass.Text = suggestion.Window.ClassName; - if (string.IsNullOrWhiteSpace(_barTitle.Text)) _barTitle.Text = suggestion.Window.Title; - } + if (string.IsNullOrWhiteSpace(_barClass.Text)) + SetSuggestionValue(_barClass, suggestion.Window.ClassName); + if (string.IsNullOrWhiteSpace(_barTitle.Text)) + SetSuggestionValue(_barTitle, suggestion.Window.Title); } - finally { _suppressBarEvents = false; } + ApplyBarDetails(); if (field == 0) RebuildWindowSuggestions(false); }; @@ -766,12 +783,29 @@ namespace pacs_win_uia.UI return box; } + private void SetSuggestionValue(ComboBox box, string raw) + { + if (box == null) return; + bool previous = _suppressBarEvents; + _suppressBarEvents = true; + try + { + box.SelectedIndex = -1; + box.Text = raw ?? string.Empty; + box.SelectionStart = box.Text.Length; + box.SelectionLength = 0; + } + finally + { + _suppressBarEvents = previous; + } + } + private static string SuggestionValue(ComboBox box) { - var selected = box.SelectedItem as WindowSuggestion; - // Text may be a user's edit even if WinForms still has a SelectedItem. - return selected != null && string.Equals(box.Text, selected.ToString(), StringComparison.Ordinal) - ? selected.Value : box.Text; + // Never derive a persisted value from SelectedItem.ToString(): it is intentionally a + // friendly description of a window, not the process/class/title condition itself. + return box == null ? string.Empty : (box.Text ?? string.Empty).Trim(); } private async void RefreshWindowSuggestionsAsync() @@ -819,7 +853,11 @@ namespace pacs_win_uia.UI private void FillWindowSuggestions(ComboBox box, int field, string process) { - string text = SuggestionValue(box); + // Snapshot at refresh completion, not before the asynchronous enumeration: current + // edits (including whitespace/caret) always win over the newly arrived suggestions. + string text = box.Text; + int selectionStart = box.SelectionStart; + int selectionLength = box.SelectionLength; box.BeginUpdate(); try { @@ -832,8 +870,9 @@ namespace pacs_win_uia.UI if (string.IsNullOrEmpty(value)) continue; box.Items.Add(new WindowSuggestion { Window = window, Value = value }); } - box.SelectedIndex = -1; - box.Text = text; + SetSuggestionValue(box, text); + box.Select(Math.Min(selectionStart, box.Text.Length), + Math.Min(selectionLength, Math.Max(0, box.Text.Length - selectionStart))); } finally { box.EndUpdate(); } } @@ -859,7 +898,10 @@ namespace pacs_win_uia.UI _barCheckStatus.Text = "正在后台检测当前草稿(只读,不执行操作)…"; try { - Task check = Task.Run(() => FloatingBarManager.CheckDisplayConditions(snapshot)); + // Diagnostic on purpose: this dialog covers the target window, so "本工具窗口遮挡" must + // not make every check fail. Runtime still counts them. + Task check = Task.Run( + () => FloatingBarManager.CheckDisplayConditions(snapshot, true)); if (await Task.WhenAny(check, Task.Delay(10000)) != check) { if (!IsDisposed && !Disposing && version == _barEditVersion) @@ -985,9 +1027,9 @@ namespace pacs_win_uia.UI Math.Min(_barControlOpacity.Maximum, bar.ControlOpacityPercent)); _barOffsetX.Value = Math.Max(_barOffsetX.Minimum, Math.Min(_barOffsetX.Maximum, bar.OffsetX)); _barOffsetY.Value = Math.Max(_barOffsetY.Minimum, Math.Min(_barOffsetY.Maximum, bar.OffsetY)); - _barProcess.Text = bar.ProcessName; - _barClass.Text = bar.WindowClass; - _barTitle.Text = bar.WindowTitleKeyword; + SetSuggestionValue(_barProcess, bar.ProcessName); + SetSuggestionValue(_barClass, bar.WindowClass); + SetSuggestionValue(_barTitle, bar.WindowTitleKeyword); _barRequireVisible.Checked = bar.RequireWindowVisible; } finally @@ -1153,9 +1195,9 @@ namespace pacs_win_uia.UI _suppressBarEvents = true; try { - _barProcess.Text = bar.ProcessName; - _barClass.Text = bar.WindowClass; - _barTitle.Text = bar.WindowTitleKeyword; + SetSuggestionValue(_barProcess, bar.ProcessName); + SetSuggestionValue(_barClass, bar.WindowClass); + SetSuggestionValue(_barTitle, bar.WindowTitleKeyword); } finally { diff --git a/tests/regression/Program.cs b/tests/regression/Program.cs index 86ef584..3a44078 100644 --- a/tests/regression/Program.cs +++ b/tests/regression/Program.cs @@ -18,6 +18,8 @@ namespace PacsWinUia.RegressionTests PersistenceTests.Register(tests); TreeRefreshTests.Register(tests); FloatingConditionsTests.Register(tests); + SettingsComboBoxTests.Register(tests); + WindowVisibilityTests.Register(tests); int passed = 0; foreach (var test in tests) { diff --git a/tests/regression/RegressionTests.csproj b/tests/regression/RegressionTests.csproj index 61d899a..893ae55 100644 --- a/tests/regression/RegressionTests.csproj +++ b/tests/regression/RegressionTests.csproj @@ -33,6 +33,8 @@ + + ControlTreeReconciler.cs diff --git a/tests/regression/SettingsComboBoxTests.cs b/tests/regression/SettingsComboBoxTests.cs new file mode 100644 index 0000000..b545da2 --- /dev/null +++ b/tests/regression/SettingsComboBoxTests.cs @@ -0,0 +1,243 @@ +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) + { + 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); + } +} diff --git a/tests/regression/WindowVisibilityTests.cs b/tests/regression/WindowVisibilityTests.cs new file mode 100644 index 0000000..01b8d3f --- /dev/null +++ b/tests/regression/WindowVisibilityTests.cs @@ -0,0 +1,78 @@ +using System; +using System.Collections.Generic; +using System.Windows.Forms; +using pacs_win_uia.Models; +using pacs_win_uia.Services; + +namespace PacsWinUia.RegressionTests +{ + /// + /// Coverage for the occlusion diagnostic used by 设置 → 悬浮按钮 → 检测显示条件. + /// The tool's own windows must not be reported as occluders there (the settings dialog itself + /// covers the target while the operator is configuring), while foreign windows still must be. + /// No UIA and no target manipulation: real Win32 windows of this test process only. + /// + internal static class WindowVisibilityTests + { + public static void Register(IList> tests) + { + tests.Add(new KeyValuePair("Own-process detection classifies tool windows", OwnProcess)); + tests.Add(new KeyValuePair("Occluder message names the blocker and never blames the tool wrongly", OccluderMessages)); + } + + private static void OwnProcess() + { + Check.True(!WindowVisibility.IsOwnProcessWindow(IntPtr.Zero), "Zero handle is not an own window"); + using (var form = new Form()) + { + form.CreateControl(); + IntPtr handle = form.Handle; + Check.True(handle != IntPtr.Zero, "Test form has no handle"); + Check.True(WindowVisibility.IsOwnProcessWindow(handle), "Own form was not recognised as own process"); + } + + // WindowEnumerationResult always excludes this process, so anything it returns is foreign. + IList foreign = new NativeWindowService().EnumerateTopLevelWindows(false); + if (foreign.Count == 0) + { + Console.WriteLine(" (no foreign window available on this desktop; foreign half skipped)"); + return; + } + + Check.True(!WindowVisibility.IsOwnProcessWindow(foreign[0].Handle), + "Foreign window was classified as own process"); + } + + private static void OccluderMessages() + { + Check.Equal(null, WindowVisibility.DescribeOccluders(null, 0, false), "Empty occluder list"); + Check.Equal(null, WindowVisibility.DescribeOccluders(new List(), 0, false), "No occluders"); + + using (var own = new Form()) + { + own.CreateControl(); + int pid = System.Diagnostics.Process.GetCurrentProcess().Id; + string ownOnly = WindowVisibility.DescribeOccluders(new List { own.Handle }, pid, true); + Check.True(ownOnly != null && ownOnly.Contains("本工具"), "Own-window occluder not named as tool window"); + Check.True(ownOnly.Contains("设置页自检"), "Own-window occluder message does not explain the diagnostic case"); + + IList foreign = new NativeWindowService().EnumerateTopLevelWindows(false); + if (foreign.Count == 0) + { + Console.WriteLine(" (no foreign window available on this desktop; mixed half skipped)"); + return; + } + + string mixed = WindowVisibility.DescribeOccluders( + new List { own.Handle, foreign[0].Handle }, pid, false); + Check.True(mixed != null && mixed.Contains("遮挡窗口"), "Mixed occluder list missing header"); + Check.True(mixed.Contains("其中 1 个是本工具窗口"), "Mixed occluder list did not count own windows"); + + string foreignOnly = WindowVisibility.DescribeOccluders( + new List { foreign[0].Handle }, pid, true); + Check.True(foreignOnly != null && !foreignOnly.Contains("本工具自己的窗口"), + "Foreign occluder was blamed on the tool"); + } + } + } +}