Files
2026-10-11 23:23:20 +00:00

561 lines
36 KiB
C#

using System.Drawing.Drawing2D;
using System.Text.Json;
namespace UCVL.VPNPlus;
/// <summary>Offline native-window fixture; no MainForm, API, token, VPN or installer.</summary>
internal static class WindowChromeSelfTest
{
internal static int Run()
{
var checks = new Dictionary<string, bool>();
var geometry = new Dictionary<string, string>();
string? error = null;
var captionAbsentThroughout = true;
bool WaitForState(Form window, FormWindowState expected, string step, Rectangle? expectedBounds = null)
{
// A single DoEvents only drains messages already queued. Do not send
// another synthetic system command while the previous transition is
// still delivering native size/style/layout notifications. Never
// retry a command or force WindowState: a missing transition fails.
var timer = System.Diagnostics.Stopwatch.StartNew();
long stableSince = -1;
string? previous = null;
var reached = false;
do
{
Application.DoEvents();
var style = ChromeNative.GetWindowLongPtr(window.Handle, ChromeNative.GwlStyle).ToInt64();
captionAbsentThroughout &= (style & ChromeNative.WsCaption) == 0;
var nativeState = (style & 0x20000000L /* WS_MINIMIZE */) != 0 ? FormWindowState.Minimized
: (style & 0x01000000L /* WS_MAXIMIZE */) != 0 ? FormWindowState.Maximized : FormWindowState.Normal;
var sample = $"state={window.WindowState}; native={nativeState}; bounds={window.Bounds}; client={window.RectangleToScreen(window.ClientRectangle)}";
var matches = window.WindowState == expected && nativeState == expected
&& (expectedBounds is null || window.Bounds == expectedBounds.Value);
if (!matches || sample != previous) stableSince = matches ? timer.ElapsedMilliseconds : -1;
previous = sample;
if (stableSince >= 0 && timer.ElapsedMilliseconds - stableSince >= 150)
{
reached = true;
break;
}
System.Threading.Thread.Sleep(10);
} while (timer.ElapsedMilliseconds < 2_000);
geometry["transition_" + step] = $"expected={expected}; stable={reached}; elapsed_ms={timer.ElapsedMilliseconds}; {previous}";
return reached;
}
try
{
checks["signed_negative_monitor_coordinates"] = ChromeGeometry.ScreenPoint(Pack(new Point(-1500, -200))) == new Point(-1500, -200);
checks["negative_monitor_workarea_offset"] = ChromeGeometry.MaximizedBounds(
new Rectangle(-1920, -1080, 1920, 1080), new Rectangle(-1920, -1040, 1920, 1040)) == new Rectangle(0, 40, 1920, 1040);
checks["left_taskbar_workarea_offset"] = ChromeGeometry.MaximizedBounds(
new Rectangle(-1920, 0, 1920, 1080), new Rectangle(-1880, 0, 1880, 1080)) == new Rectangle(40, 0, 1880, 1080);
foreach (var dpi in new[] { 96, 120, 144, 192, 240 })
{
var border = (int)Math.Round(6 * dpi / 96.0);
var size = new Size(900 * dpi / 96, 680 * dpi / 96);
var cases = new (Point Point, int Hit)[]
{
(new(0, 0), 13), (new(size.Width - 1, 0), 14),
(new(0, size.Height - 1), 16), (new(size.Width - 1, size.Height - 1), 17),
(new(0, size.Height / 2), 10), (new(size.Width - 1, size.Height / 2), 11),
(new(size.Width / 2, 0), 12), (new(size.Width / 2, size.Height - 1), 15),
(new(size.Width / 2, size.Height / 2), 1)
};
checks[$"eight_resize_edges_{dpi}dpi"] = cases.All(c => ChromeGeometry.ResizeHitTest(size, c.Point, border, true) == c.Hit);
checks[$"no_resize_when_maximized_{dpi}dpi"] = cases.All(c => ChromeGeometry.ResizeHitTest(size, c.Point, border, false) == 1);
}
CheckLoginModes(checks, WaitForState);
using var form = new TestForm
{
Text = "纵横家 · 离线窗口外壳自测",
ClientSize = new Size(700, 400), MinimumSize = new Size(500, 300),
StartPosition = FormStartPosition.Manual, Location = new Point(80, 80),
// Only this owned fixture needs an unobstructed input target.
// Preserve it across HWND recreation without changing the app.
AutoScaleMode = AutoScaleMode.Dpi, ShowInTaskbar = false, TopMost = true
};
using var header = new TestHeader { Dock = DockStyle.Top, Height = 100 };
using var title = new Label { Text = "Logo 与软件名称", Bounds = new Rectangle(30, 36, 200, 35), BackColor = Color.Transparent };
using var combo = new ComboBox { Bounds = new Rectangle(280, 42, 130, 28), DropDownStyle = ComboBoxStyle.DropDownList };
combo.Items.Add("应保持交互的下拉框"); combo.SelectedIndex = 0;
using var link = new LinkLabel { Text = "交互链接", Bounds = new Rectangle(420, 42, 100, 30), BackColor = Color.Transparent };
header.Controls.AddRange([title, combo, link]);
using var body = new Panel { Dock = DockStyle.Fill, BackColor = Color.Azure };
form.Controls.AddRange([body, header]);
body.BringToFront();
var exitRequests = 0;
using var chrome = new WindowChrome(form, header, () => { exitRequests++; form.Close(); });
var closeEvents = 0;
// Synthetic close-to-tray contract. The real MainForm branch is
// exercised separately by existing StartupSelfTest --uiOnly mode.
form.FormClosing += (_, e) => { closeEvents++; e.Cancel = true; form.Hide(); };
form.Show();
var initiallyReady = WaitForState(form, FormWindowState.Normal, "initial_show");
chrome.LayoutButtons();
checks["client_canvas_replaces_entire_caption"] = initiallyReady && form.RectangleToScreen(form.ClientRectangle) == form.Bounds;
checks["native_sizable_style_preserved"] = (ChromeNative.GetWindowLongPtr(form.Handle, ChromeNative.GwlStyle).ToInt64() & ChromeNative.NativeFrameStyles) == ChromeNative.NativeFrameStyles;
checks["native_caption_style_absent"] = NativeCaptionAbsent(form);
// Simulate the real managed refresh path attempting to add a native
// title bar. The hooked HWND must remove it, not merely hide paint.
var initialStyle = ChromeNative.GetWindowLongPtr(form.Handle, ChromeNative.GwlStyle).ToInt64();
ChromeNative.SetWindowLongPtr(form.Handle, ChromeNative.GwlStyle, (IntPtr)(initialStyle | ChromeNative.WsCaption));
checks["native_caption_cannot_return_on_style_refresh"] = NativeCaptionAbsent(form);
checks["system_menu_available_for_alt_space"] = ChromeNative.GetSystemMenu(form.Handle, false) != IntPtr.Zero;
checks["caption_blank_native_drag"] = Hit(form, header.PointToScreen(new Point(240, 20))) == ChromeNative.HtCaption;
checks["caption_label_native_drag"] = Hit(form, title.PointToScreen(new Point(8, 8))) == ChromeNative.HtCaption;
checks["label_forwards_hit_to_form"] = Hit(title, title.PointToScreen(new Point(8, 8))) == ChromeNative.HtTransparent;
checks["combo_keeps_client_input"] = Hit(form, combo.PointToScreen(new Point(10, 10))) == ChromeNative.HtClient && Hit(combo, combo.PointToScreen(new Point(10, 10))) != ChromeNative.HtTransparent;
checks["link_keeps_client_input"] = Hit(form, link.PointToScreen(new Point(10, 10))) == ChromeNative.HtClient;
checks["buttons_keep_client_input"] = new[] { chrome.MinimizeButton }
.All(b => Hit(form, b.PointToScreen(new Point(b.Width / 2, b.Height / 2))) == ChromeNative.HtClient);
foreach (var button in new[] { chrome.MinimizeButton })
checks["entire_button_perimeter_clickable_" + button.AccessibleName] = PerimeterClickable(form, button);
checks["resize_band_above_and_beside_buttons_remains"] =
Hit(form, form.PointToScreen(new Point(chrome.MinimizeButton.Left + 2, 0))) == 12 &&
Hit(form, form.PointToScreen(new Point(form.ClientSize.Width - 1, chrome.MinimizeButton.Top + 10))) == 11 &&
Hit(form, form.PointToScreen(new Point(form.ClientSize.Width - 1, 0))) == 14;
checks["buttons_real_accessible_keyboard_controls"] = new[] { chrome.MinimizeButton }
.All(b => b.TabStop && b.AccessibleRole == AccessibleRole.PushButton && !string.IsNullOrWhiteSpace(b.AccessibleName));
checks["buttons_do_not_whitewash_header"] = new[] { chrome.MinimizeButton }.All(b => b.BackColor == Color.Transparent);
checks["body_edge_forwards_resize"] = Hit(body, form.PointToScreen(new Point(1, 150))) == ChromeNative.HtTransparent;
checks["dwm_native_caption_rendering_disabled"] =
ChromeNative.DwmGetWindowAttribute(form.Handle, 1 /* DWMWA_NCRENDERING_ENABLED */, out var nativeRendering, sizeof(int)) == 0
&& nativeRendering == 0;
var activationPreserved = true;
foreach (var active in new[] { false, true, false, true })
{
var result = ChromeNative.SendMessage(form.Handle, ChromeNative.WmNcActivate, active ? (IntPtr)1 : IntPtr.Zero, IntPtr.Zero);
activationPreserved &= active || result != IntPtr.Zero;
ChromeNative.SendMessage(form.Handle, ChromeNative.WmNcPaint, (IntPtr)1, IntPtr.Zero);
}
checks["inactive_activation_not_blocked"] = activationPreserved;
foreach (var message in new[] { ChromeNative.WmThemeChanged, ChromeNative.WmDwmCompositionChanged })
ChromeNative.SendMessage(form.Handle, message, IntPtr.Zero, IntPtr.Zero);
checks["native_caption_stays_disabled_after_theme_change"] =
ChromeNative.DwmGetWindowAttribute(form.Handle, 1, out nativeRendering, sizeof(int)) == 0 && nativeRendering == 0;
checks["native_caption_style_absent_after_activation_and_theme"] = NativeCaptionAbsent(form);
checks["caption_background_layer_enabled"] = !HasOpaqueStyle(chrome.MinimizeButton);
checks["caption_old_opaque_style_fails_dirty_repaint"] = RejectsOpaqueBackgroundSkip(chrome.MinimizeButton);
foreach (var button in new[] { chrome.MinimizeButton })
checks["caption_repaint_no_ghost_or_hover_accumulation_" + button.AccessibleName] = RepaintStable(button);
// Also cover the production header's direct ScenicTheme branch,
// not only the fixture's simple gradient background.
using (var scenicHeader = new BrandHeaderPanel { Size = header.Size })
using (var scenicButton = new CaptionButton(CaptionAction.Minimize) { Bounds = chrome.MinimizeButton.Bounds })
{
scenicHeader.Controls.Add(scenicButton);
checks["scenic_caption_old_opaque_style_fails_dirty_repaint"] = RejectsOpaqueBackgroundSkip(scenicButton);
checks["scenic_caption_repaint_recovers_after_opaque_negative_control"] =
!HasOpaqueStyle(scenicButton) && RepaintStable(scenicButton);
}
using (var image = new Bitmap(form.Width, form.Height))
{
form.DrawToBitmap(image, new Rectangle(Point.Empty, image.Size));
image.Save(Path.Combine(AppContext.BaseDirectory, "window-chrome-offline.png"));
// Outside glyphs/highlights, custom buttons preserve the same
// blue header gradient as their adjacent caption pixels.
var row = chrome.MinimizeButton.Top + Math.Min(12, chrome.MinimizeButton.Height - 2);
var sample = image.GetPixel(chrome.MinimizeButton.Left + 7, row);
var adjacent = image.GetPixel(chrome.MinimizeButton.Left - 7, row);
checks["rendered_caption_background_continuous"] = Distance(sample, adjacent) <= 5 && sample != Color.White;
using var actualHeader = new Bitmap(header.Width, header.Height);
header.DrawToBitmap(actualHeader, new Rectangle(Point.Empty, actualHeader.Size));
var probes = new[]
{
new Point(8, 8), new Point(100, 12), new Point(chrome.MinimizeButton.Left + 7, row),
new Point(chrome.MinimizeButton.Left + chrome.MinimizeButton.Width / 2, chrome.MinimizeButton.Top + chrome.MinimizeButton.Height / 2)
};
checks["draw_to_bitmap_prints_real_header_not_invented_native_caption"] = probes.All(p =>
Distance(image.GetPixel(header.Left + p.X, header.Top + p.Y), actualHeader.GetPixel(p.X, p.Y)) <= 5);
}
var restoreBounds = form.Bounds;
geometry["original"] = restoreBounds.ToString();
checks["only_minimize_caption_button_present"] = header.Controls.OfType<CaptionButton>().Count() == 1;
checks["maximize_box_disabled"] = !form.MaximizeBox &&
(ChromeNative.GetWindowLongPtr(form.Handle, ChromeNative.GwlStyle).ToInt64() & ChromeNative.WsMaximizeBox) == 0;
ChromeNative.SendMessage(form.Handle, ChromeNative.WmSysCommand, (IntPtr)ChromeNative.ScMaximize, IntPtr.Zero);
checks["system_maximize_blocked"] = WaitForState(form, FormWindowState.Normal, "blocked_maximize", restoreBounds);
ChromeNative.SendMessage(form.Handle, 0xa3 /* WM_NCLBUTTONDBLCLK */, (IntPtr)ChromeNative.HtCaption,
Pack(header.PointToScreen(new Point(240, 20))));
checks["caption_double_click_does_not_maximize"] = WaitForState(form, FormWindowState.Normal, "blocked_double_click", restoreBounds);
chrome.MinimizeButton.PerformClick();
var minimized = WaitForState(form, FormWindowState.Minimized, "minimize_button");
checks["minimize_button_native_state"] = minimized && form.WindowState == FormWindowState.Minimized;
ChromeNative.SendMessage(form.Handle, ChromeNative.WmSysCommand, (IntPtr)ChromeNative.ScRestore, IntPtr.Zero);
var systemRestored = WaitForState(form, FormWindowState.Normal, "system_restore", restoreBounds);
checks["system_restore_after_minimize"] = systemRestored && form.WindowState == FormWindowState.Normal;
var mouseProbe = ProbeMinimizeInputAsync(form, chrome.MinimizeButton, mouse: true);
while (!mouseProbe.IsCompleted) { Application.DoEvents(); System.Threading.Thread.Sleep(10); }
var mouseMinimize = mouseProbe.GetAwaiter().GetResult();
checks["mouse_down_up_click_minimizes_plain_form"] = mouseMinimize.Passed;
geometry["plain_form_mouse_minimize"] = JsonSerializer.Serialize(mouseMinimize);
ChromeNative.SendMessage(form.Handle, ChromeNative.WmSysCommand, (IntPtr)ChromeNative.ScRestore, IntPtr.Zero);
checks["mouse_minimize_plain_form_restores"] = WaitForState(form, FormWindowState.Normal, "mouse_restore", restoreBounds);
chrome.MinimizeButton.PerformClick();
checks["minimize_waits_for_mouse_message_return"] = form.WindowState == FormWindowState.Normal;
form.RecreateForTest();
checks["pending_minimize_cancelled_on_handle_recreation"] =
WaitForState(form, FormWindowState.Normal, "pending_recreate", restoreBounds);
var recreatedMouseProbe = ProbeMinimizeInputAsync(form, chrome.MinimizeButton, mouse: true);
while (!recreatedMouseProbe.IsCompleted) { Application.DoEvents(); System.Threading.Thread.Sleep(10); }
var recreatedMouseMinimize = recreatedMouseProbe.GetAwaiter().GetResult();
checks["mouse_minimize_works_after_pending_handle_recreation"] = recreatedMouseMinimize.Passed;
geometry["recreated_form_mouse_minimize"] = JsonSerializer.Serialize(recreatedMouseMinimize);
ChromeNative.SendMessage(form.Handle, ChromeNative.WmSysCommand, (IntPtr)ChromeNative.ScRestore, IntPtr.Zero);
checks["recreated_form_restores_after_mouse_minimize"] =
WaitForState(form, FormWindowState.Normal, "recreated_mouse_restore", restoreBounds);
checks["caption_repaint_stable_after_native_window_transitions"] =
new[] { chrome.MinimizeButton }.All(RepaintStable);
ChromeNative.SendMessage(form.Handle, ChromeNative.WmSysCommand, (IntPtr)ChromeNative.ScClose, IntPtr.Zero);
Application.DoEvents();
checks["system_close_alt_f4_blocked"] = closeEvents == 0 && exitRequests == 0 && form.Visible && !form.IsDisposed;
ChromeNative.SendMessage(form.Handle, ChromeNative.WmSysCommand, (IntPtr)ChromeNative.ScExplicitExit, IntPtr.Zero);
Application.DoEvents();
checks["explicit_menu_exit_dispatches_cancelable_formclosing"] = exitRequests == 1 && closeEvents == 1 && !form.Visible && !form.IsDisposed;
checks["native_caption_absent_through_every_state_transition"] = captionAbsentThroughout && NativeCaptionAbsent(form);
}
catch (Exception e) { error = e.ToString(); }
var passed = error is null && checks.Count > 20 && checks.Values.All(v => v);
File.WriteAllText(Path.Combine(AppContext.BaseDirectory, "window-chrome-self-test.json"), JsonSerializer.Serialize(new
{
passed, checks, geometry, error, scope = "isolated synthetic WinForms window, not installed client or network acceptance",
network_modified = false, installed_client_modified = false,
untested = new[] { "physical multi-monitor DPI transition", "actual mouse drag/snap", "Windows 11 snap-layout hover UI" }
}, new JsonSerializerOptions { WriteIndented = true }));
return passed ? 0 : 27;
}
private static void CheckLoginModes(Dictionary<string, bool> checks,
Func<Form, FormWindowState, string, Rectangle?, bool> waitForState)
{
// This owned window only records exit requests. It never constructs a
// client, authenticates, disconnects, or runs production exit logic.
using var form = new TestForm
{
ClientSize = new Size(500, 220), StartPosition = FormStartPosition.Manual,
Location = new Point(100, 100), ShowInTaskbar = false, TopMost = true
};
using var header = new TestHeader { Dock = DockStyle.Top, Height = 80 };
form.Controls.Add(header);
var exitRequests = 0;
var closeEvents = 0;
form.FormClosing += (_, e) => { closeEvents++; e.Cancel = true; };
using var chrome = new WindowChrome(form, header, () => exitRequests++);
form.Show();
var bounds = form.Bounds;
checks["mode_fixture_initially_ready"] = waitForState(form, FormWindowState.Normal, "mode_initial", bounds);
var button = chrome.MinimizeButton;
var buttonBounds = button.Bounds;
string ToolTipText() => ((ToolTip)typeof(WindowChrome).GetField("_toolTip",
System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic)!.GetValue(chrome)!).GetToolTip(button) ?? "";
checks["default_mode_preserves_minimize_baseline"] = !chrome.LoginMode && button.Action == CaptionAction.Minimize
&& button.AccessibleName == "最小化" && ToolTipText() == "最小化";
using var minimizeImage = new Bitmap(button.Width, button.Height);
button.DrawToBitmap(minimizeImage, new Rectangle(Point.Empty, minimizeImage.Size));
chrome.SetLoginMode(true);
using var closeImage = new Bitmap(button.Width, button.Height);
button.DrawToBitmap(closeImage, new Rectangle(Point.Empty, closeImage.Size));
checks["login_mode_switches_single_button_glyph_accessibility_and_tooltip"] = chrome.LoginMode
&& button.Action == CaptionAction.Close && button.AccessibleName == "退出软件" && ToolTipText() == "退出软件"
&& button.Bounds == buttonBounds && header.Controls.OfType<CaptionButton>().Count() == 1
&& Enumerable.Range(0, button.Width).Any(x => Enumerable.Range(0, button.Height)
.Any(y => minimizeImage.GetPixel(x, y) != closeImage.GetPixel(x, y)));
checks["login_close_repaint_stable"] = RepaintStable(button);
button.PerformClick();
checks["login_close_button_requests_existing_exit_only"] = exitRequests == 1 && closeEvents == 0
&& form.Visible && form.WindowState == FormWindowState.Normal;
ChromeNative.SendMessage(form.Handle, ChromeNative.WmSysCommand, (IntPtr)ChromeNative.ScClose, IntPtr.Zero);
checks["login_system_close_requests_existing_exit_only"] = exitRequests == 2 && closeEvents == 0 && form.Visible;
ChromeNative.SendMessage(form.Handle, ChromeNative.WmSysCommand, (IntPtr)ChromeNative.ScMaximize, IntPtr.Zero);
checks["login_system_maximize_remains_blocked"] = waitForState(form, FormWindowState.Normal, "login_blocked_maximize", bounds);
ChromeNative.SendMessage(form.Handle, ChromeNative.WmSysCommand, (IntPtr)ChromeNative.ScExplicitExit, IntPtr.Zero);
checks["login_explicit_menu_exit_preserved"] = exitRequests == 3 && closeEvents == 0;
chrome.SetLoginMode(false);
checks["dashboard_mode_restores_minimize_accessibility_and_tooltip"] = !chrome.LoginMode
&& button.Action == CaptionAction.Minimize && button.AccessibleName == "最小化" && ToolTipText() == "最小化";
ChromeNative.SendMessage(form.Handle, ChromeNative.WmSysCommand, (IntPtr)ChromeNative.ScClose, IntPtr.Zero);
checks["dashboard_system_close_does_not_request_exit"] = exitRequests == 3 && closeEvents == 0 && form.Visible;
button.PerformClick();
chrome.SetLoginMode(true);
checks["pending_minimize_cancelled_on_login_mode"] = waitForState(form, FormWindowState.Normal, "pending_login_mode", bounds);
chrome.SetLoginMode(false);
button.PerformClick();
chrome.SetLoginMode(true);
chrome.SetLoginMode(false);
checks["pending_minimize_cancelled_on_mode_round_trip"] = waitForState(form, FormWindowState.Normal, "pending_mode_round_trip", bounds);
button.PerformClick();
chrome.SetLoginMode(false); // An unchanged mode must not cancel this click.
checks["new_minimize_after_mode_change_and_same_mode_call_works"] = waitForState(form, FormWindowState.Minimized, "new_mode_minimize", null);
ChromeNative.SendMessage(form.Handle, ChromeNative.WmSysCommand, (IntPtr)ChromeNative.ScRestore, IntPtr.Zero);
checks["mode_fixture_restores_after_minimize"] = waitForState(form, FormWindowState.Normal, "mode_restore", bounds);
button.PerformClick(); // The old callback is still queued.
chrome.SetLoginMode(true);
chrome.SetLoginMode(false);
var newerPendingPreserved = false;
form.BeginInvoke(() => newerPendingPreserved = (bool)typeof(WindowChrome).GetField("_minimizePending",
System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic)!.GetValue(chrome)!);
button.PerformClick(); // Queue the new callback behind the observation.
checks["old_mode_callback_does_not_clear_new_pending_minimize"] =
waitForState(form, FormWindowState.Minimized, "old_and_new_mode_callbacks", null) && newerPendingPreserved;
ChromeNative.SendMessage(form.Handle, ChromeNative.WmSysCommand, (IntPtr)ChromeNative.ScRestore, IntPtr.Zero);
checks["old_and_new_mode_callbacks_restore_normally"] = waitForState(form, FormWindowState.Normal, "mode_callbacks_restore", bounds);
var center = new Point(button.Width / 2, button.Height / 2);
ChromeNative.SendMessage(button.Handle, 0x201 /* WM_LBUTTONDOWN */, (IntPtr)1, Pack(center));
var captured = button.Capture;
chrome.SetLoginMode(true);
var released = !button.Capture;
ChromeNative.SendMessage(button.Handle, 0x202 /* WM_LBUTTONUP */, IntPtr.Zero, Pack(center));
Application.DoEvents();
checks["mode_switch_releases_capture_without_converting_held_click_to_exit"] = captured && released
&& exitRequests == 3 && closeEvents == 0 && form.WindowState == FormWindowState.Normal;
chrome.SetLoginMode(false);
EventHandler reentrantMode = (_, _) => { if (!button.Capture && chrome.LoginMode) chrome.SetLoginMode(false); };
button.MouseCaptureChanged += reentrantMode;
try
{
ChromeNative.SendMessage(button.Handle, 0x201 /* WM_LBUTTONDOWN */, (IntPtr)1, Pack(center));
chrome.SetLoginMode(true);
ChromeNative.SendMessage(button.Handle, 0x202 /* WM_LBUTTONUP */, IntPtr.Zero, Pack(center));
checks["capture_change_reentrant_mode_keeps_latest_action"] = !chrome.LoginMode && !button.Capture
&& button.Action == CaptionAction.Minimize && button.AccessibleName == "最小化" && ToolTipText() == "最小化"
&& exitRequests == 3 && closeEvents == 0;
}
finally { button.MouseCaptureChanged -= reentrantMode; }
chrome.SetLoginMode(true);
form.RecreateForTest();
checks["login_mode_survives_handle_recreation"] = waitForState(form, FormWindowState.Normal, "login_recreate", bounds)
&& chrome.LoginMode && button.Action == CaptionAction.Close && button.AccessibleName == "退出软件" && ToolTipText() == "退出软件";
button.PerformClick();
checks["login_close_works_after_handle_recreation"] = exitRequests == 4 && closeEvents == 0;
chrome.SetLoginMode(false);
ChromeNative.SendMessage(form.Handle, ChromeNative.WmSysCommand, (IntPtr)ChromeNative.ScExplicitExit, IntPtr.Zero);
checks["dashboard_explicit_menu_exit_preserved"] = exitRequests == 5 && closeEvents == 0;
}
private static int Distance(Color a, Color b) => Math.Abs(a.R - b.R) + Math.Abs(a.G - b.G) + Math.Abs(a.B - b.B);
internal sealed record MinimizeInputProbe(bool Mouse, bool PointTargetsButton, bool CapturedAfterDown,
int Clicks, bool CapturedDuringClick, bool ManagedMinimized, bool NativeMinimized, bool Visible,
long ReadyElapsedMilliseconds, bool ReadyTimedOut)
{
public bool Passed => (!Mouse || PointTargetsButton && CapturedAfterDown) && Clicks == 1
&& ManagedMinimized && NativeMinimized && Visible;
}
// Call only for a fixture created by the caller. No global input injection,
// external HWND search, live client, token, process or network interaction.
internal static Task<MinimizeInputProbe> ProbeMinimizeInputAsync(Form form, CaptionButton button, bool mouse)
{
form.BringToFront();
form.Activate();
var center = new Point(button.Width / 2, button.Height / 2);
var pointTargetsButton = false;
var capturedAfterDown = false;
var clicks = 0;
var capturedDuringClick = false;
var readyWatch = System.Diagnostics.Stopwatch.StartNew();
long readyElapsedMilliseconds = 0;
long stableSince = -1;
var readyTimedOut = false;
var inputDispatched = false;
var completion = new TaskCompletionSource<MinimizeInputProbe>(TaskCreationOptions.RunContinuationsAsynchronously);
var readyTimer = new System.Windows.Forms.Timer { Interval = 25 };
var settleTimer = new System.Windows.Forms.Timer { Interval = 350 };
void Clicked(object? sender, EventArgs e) { clicks++; capturedDuringClick |= button.Capture; }
void Cleanup()
{
readyTimer.Stop();
readyTimer.Dispose();
settleTimer.Stop();
settleTimer.Dispose();
button.Click -= Clicked;
if (!button.IsDisposed) button.Capture = false;
}
void DispatchOnce()
{
if (inputDispatched) return;
inputDispatched = true;
readyTimer.Stop();
if (mouse)
{
ChromeNative.SendMessage(button.Handle, 0x201 /* WM_LBUTTONDOWN */, (IntPtr)1 /* MK_LBUTTON */, Pack(center));
capturedAfterDown = button.Capture;
ChromeNative.SendMessage(button.Handle, 0x202 /* WM_LBUTTONUP */, IntPtr.Zero, Pack(center));
}
else button.PerformClick();
settleTimer.Start();
}
readyTimer.Tick += (_, _) =>
{
try
{
if (readyTimedOut || inputDispatched) return;
// Let activation/layout settle on this UI thread, then require
// 150 ms of button hits. Readiness plus settlement budgets 2.35 s.
readyElapsedMilliseconds = readyWatch.ElapsedMilliseconds;
if (readyElapsedMilliseconds >= 2_000)
{
// Preserve a failed readiness result without sending input.
// The unchanged settlement phase still observes final state.
readyTimer.Stop();
readyTimedOut = true;
pointTargetsButton = false;
settleTimer.Start();
return;
}
center = new Point(button.Width / 2, button.Height / 2);
var screen = button.PointToScreen(center);
var targetsButton = WindowFromPoint(new ChromeNative.NativePoint(screen)) == button.Handle;
if (!targetsButton) stableSince = -1;
else if (stableSince < 0) stableSince = readyElapsedMilliseconds;
if (stableSince >= 0 && readyElapsedMilliseconds - stableSince >= 150)
{
pointTargetsButton = true;
DispatchOnce();
}
}
catch (Exception error) { Cleanup(); completion.TrySetException(error); }
};
settleTimer.Tick += (_, _) =>
{
// GetCapture is thread-local. Complete through the fixture's UI
// loop even when Run() has no installed synchronization context.
try
{
var style = ChromeNative.GetWindowLongPtr(form.Handle, ChromeNative.GwlStyle).ToInt64();
completion.SetResult(new(mouse, pointTargetsButton, capturedAfterDown, clicks, capturedDuringClick,
form.WindowState == FormWindowState.Minimized, (style & 0x20000000L /* WS_MINIMIZE */) != 0, form.Visible,
ReadyElapsedMilliseconds: readyElapsedMilliseconds, ReadyTimedOut: readyTimedOut));
}
catch (Exception error) { completion.SetException(error); }
finally { Cleanup(); }
};
button.Click += Clicked;
try
{
if (mouse) readyTimer.Start();
else
{
var screen = button.PointToScreen(center);
pointTargetsButton = WindowFromPoint(new ChromeNative.NativePoint(screen)) == button.Handle;
DispatchOnce();
}
}
catch (Exception error) { Cleanup(); completion.SetException(error); }
return completion.Task;
}
[System.Runtime.InteropServices.DllImport("user32.dll")]
private static extern IntPtr WindowFromPoint(ChromeNative.NativePoint point);
private static bool NativeCaptionAbsent(Form form) =>
(ChromeNative.GetWindowLongPtr(form.Handle, ChromeNative.GwlStyle).ToInt64() & ChromeNative.WsCaption) == 0;
private static bool PerimeterClickable(Form form, CaptionButton button)
{
// Test every edge pixel, not only the center: resize hit-testing starts
// at the child HWND and must not steal the top/right part of a button.
var points = Enumerable.Range(0, button.Width).SelectMany(x => new[] { new Point(x, 0), new Point(x, button.Height - 1) })
.Concat(Enumerable.Range(0, button.Height).SelectMany(y => new[] { new Point(0, y), new Point(button.Width - 1, y) }));
return points.All(p => Hit(form, button.PointToScreen(p)) == ChromeNative.HtClient &&
Hit(button, button.PointToScreen(p)) == ChromeNative.HtClient);
}
private static bool RepaintStable(CaptionButton button)
{
// Print only this synthetic HWND into the same dirty backing surface.
// WM_PRINTCLIENT uses Control.OnPrint -> PaintWithErrorHandling, which
// honors Opaque just like WM_PAINT. Never call background/foreground
// overrides directly: that would hide the inherited-Opaque regression.
var flags = System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic;
var hot = typeof(CaptionButton).GetField("_hot", flags)!;
var pressed = typeof(CaptionButton).GetField("_pressed", flags)!;
using var buffer = new Bitmap(button.Width, button.Height);
void Draw(bool hover, bool down)
{
using var graphics = Graphics.FromImage(buffer);
hot.SetValue(button, hover); pressed.SetValue(button, down);
var hdc = graphics.GetHdc();
try
{
ChromeNative.SendMessage(button.Handle, 0x318 /* WM_PRINTCLIENT */, hdc,
(IntPtr)(0x4 /* PRF_CLIENT */ | 0x8 /* PRF_ERASEBKGND */));
}
finally { graphics.ReleaseHdc(hdc); }
}
void Dirty()
{
using var graphics = Graphics.FromImage(buffer);
graphics.Clear(Color.White);
using var font = Brand.Font(18, FontStyle.Bold);
graphics.DrawString("账号登录", font, Brushes.Magenta, PointF.Empty);
}
bool Same(Bitmap expected)
{
for (var y = 0; y < buffer.Height; y++)
for (var x = 0; x < buffer.Width; x++)
if (buffer.GetPixel(x, y) != expected.GetPixel(x, y)) return false;
return true;
}
try
{
Draw(false, false); using var idle = new Bitmap(buffer);
// This is the first comparison so the Opaque=true negative control
// proves specifically that dirty pixels survive a normal repaint.
Dirty(); Draw(false, false); if (!Same(idle)) return false;
Draw(true, false); using var hover = new Bitmap(buffer);
if (Same(idle)) return false; // highlights must actually be exercised
for (var i = 0; i < 12; i++)
{
Draw(true, false); if (!Same(hover)) return false;
Draw(true, true); Draw(false, false); if (!Same(idle)) return false;
Dirty();
Draw(false, false); if (!Same(idle)) return false;
}
return true;
}
finally { hot.SetValue(button, false); pressed.SetValue(button, false); button.Invalidate(); }
}
private static bool HasOpaqueStyle(Control control) =>
(bool)typeof(Control).GetMethod("GetStyle", System.Reflection.BindingFlags.Instance |
System.Reflection.BindingFlags.NonPublic)!.Invoke(control, [ControlStyles.Opaque])!;
private static bool RejectsOpaqueBackgroundSkip(CaptionButton button)
{
var setStyle = typeof(Control).GetMethod("SetStyle", System.Reflection.BindingFlags.Instance |
System.Reflection.BindingFlags.NonPublic)!;
var original = HasOpaqueStyle(button);
try
{
setStyle.Invoke(button, [ControlStyles.Opaque, true]);
return !RepaintStable(button);
}
finally { setStyle.Invoke(button, [ControlStyles.Opaque, original]); }
}
private static IntPtr Pack(Point p) => (IntPtr)unchecked((int)((ushort)p.X | ((uint)(ushort)p.Y << 16)));
private static int Hit(Control control, Point screen) => (int)ChromeNative.SendMessage(control.Handle, ChromeNative.WmNcHitTest, IntPtr.Zero, Pack(screen));
private sealed class TestForm : Form
{
internal void RecreateForTest() => RecreateHandle();
}
private sealed class TestHeader : Panel
{
internal TestHeader() => DoubleBuffered = true;
protected override void OnPaintBackground(PaintEventArgs e)
{
using var brush = new LinearGradientBrush(ClientRectangle, Color.FromArgb(213, 244, 252), Color.FromArgb(125, 203, 218), LinearGradientMode.Vertical);
e.Graphics.FillRectangle(brush, ClientRectangle);
}
}
}