diff --git a/PdVm.Runtime/PdVmWinFormsApplication.cs b/PdVm.Runtime/PdVmWinFormsApplication.cs
index 080d5290..e00b9778 100644
--- a/PdVm.Runtime/PdVmWinFormsApplication.cs
+++ b/PdVm.Runtime/PdVmWinFormsApplication.cs
@@ -63,12 +63,12 @@ internal PdVmWinFormsApplicationSession(
_onDispose = onDispose;
}
- public bool HasMainForm => _mainForm is not null;
+ public bool HasMainForm => Volatile.Read(ref _mainForm) is not null;
public void RunMessageLoop()
{
EnsureUiThread();
- var form = _mainForm ?? throw new InvalidOperationException(
+ var form = Volatile.Read(ref _mainForm) ?? throw new InvalidOperationException(
"the RSS program did not register a main form with EventLoop::Show");
var formType = Type.GetType(
"System.Windows.Forms.Form, System.Windows.Forms",
@@ -95,7 +95,8 @@ internal void RegisterMainForm(object form)
{
ArgumentNullException.ThrowIfNull(form);
EnsureUiThread();
- if (_mainForm is not null && !ReferenceEquals(_mainForm, form))
+ var existing = Volatile.Read(ref _mainForm);
+ if (existing is not null && !ReferenceEquals(existing, form))
{
throw new InvalidOperationException("a Windows Forms program can register only one main form");
}
@@ -104,7 +105,47 @@ internal void RegisterMainForm(object form)
BindingFlags.Public | BindingFlags.Instance)?.GetValue(form) ??
throw new InvalidOperationException(
$"{form.GetType().FullName} does not expose a window handle");
- _mainForm = form;
+ Volatile.Write(ref _mainForm, form);
+ }
+
+ ///
+ /// Closes this session's main form so that returns.
+ /// Unlike Application.Exit, which tears down every message loop in the process,
+ /// this only ends the loop owned by this session and may be called from any thread.
+ ///
+ public bool CloseMainForm()
+ {
+ var form = Volatile.Read(ref _mainForm);
+ if (form is null)
+ {
+ return false;
+ }
+
+ var beginInvoke = form.GetType().GetMethod(
+ "BeginInvoke",
+ BindingFlags.Public | BindingFlags.Instance,
+ binder: null,
+ types: [typeof(Delegate)],
+ modifiers: null);
+ if (beginInvoke is null)
+ {
+ return false;
+ }
+
+ // Route through the same close path as EventLoop::Close so that a bound
+ // FormClosing callback does not veto the shutdown.
+ Action action = () => PdVmWinFormsEventLoop.Close(form);
+ try
+ {
+ _ = beginInvoke.Invoke(form, [action]);
+ return true;
+ }
+ catch (TargetInvocationException exception)
+ when (exception.InnerException is InvalidOperationException or ObjectDisposedException)
+ {
+ // The window handle is already gone, so the loop has nothing left to close.
+ return false;
+ }
}
internal PdVmScriptCallback CreateUnitCallback(
diff --git a/PdVm.Tests/PdVmDotNetHostTests.cs b/PdVm.Tests/PdVmDotNetHostTests.cs
index 430ae525..87691e06 100644
--- a/PdVm.Tests/PdVmDotNetHostTests.cs
+++ b/PdVm.Tests/PdVmDotNetHostTests.cs
@@ -2,6 +2,7 @@
namespace PdVm.Tests;
+[Collection(WinFormsCollection.Name)]
public sealed class PdVmDotNetHostTests
{
[Fact]
@@ -67,7 +68,7 @@ public void ConstructsWindowsFormOnStaThreadWithoutCompileTimeWindowsDependency(
{
try
{
- Assert.True(PdVmDotNetHost.InitializeWindowsFormsApplication());
+ Assert.True(WinFormsTestSupport.Initialize());
var host = new PdVmDotNetHost(allowDynamicSystemCalls: true);
Assert.True(host.CanResolveType("System.Windows.Forms.Form"));
var handle = ReturnValue(host.Call(
diff --git a/PdVm.Tests/PdVmMinesweeperTests.cs b/PdVm.Tests/PdVmMinesweeperTests.cs
index 90a8130a..5d915547 100644
--- a/PdVm.Tests/PdVmMinesweeperTests.cs
+++ b/PdVm.Tests/PdVmMinesweeperTests.cs
@@ -5,6 +5,7 @@
namespace PdVm.Tests;
+[Collection(WinFormsCollection.Name)]
public sealed class PdVmMinesweeperTests
{
[Fact]
@@ -65,7 +66,7 @@ pub fn test_cell(index: int) -> [int] {
{
try
{
- PdVmDotNetHost.InitializeWindowsFormsApplication();
+ _ = WinFormsTestSupport.Initialize();
using var program = Assert.IsAssignableFrom(
PdVmAssemblyLoader.CreateProgram(Assembly.Load(File.ReadAllBytes(outputPath))));
var host = PdVmDefaultHost.CreateConsoleHost();
diff --git a/PdVm.Tests/PdVmTypedDotNetInteropTests.cs b/PdVm.Tests/PdVmTypedDotNetInteropTests.cs
index 3ca3fd08..01ced69e 100644
--- a/PdVm.Tests/PdVmTypedDotNetInteropTests.cs
+++ b/PdVm.Tests/PdVmTypedDotNetInteropTests.cs
@@ -4,6 +4,7 @@
namespace PdVm.Tests;
+[Collection(WinFormsCollection.Name)]
public sealed class PdVmTypedDotNetInteropTests
{
[Fact]
@@ -377,7 +378,7 @@ public void WinFormsButtonClickInvokesRssCallbackOnTheOwningStaThread()
{
try
{
- _ = PdVmDotNetHost.InitializeWindowsFormsApplication();
+ _ = WinFormsTestSupport.Initialize();
using var program = Assert.IsAssignableFrom(
PdVmAssemblyLoader.CreateProgram(Assembly.Load(File.ReadAllBytes(output))));
var host = PdVmDefaultHost.CreateConsoleHost();
@@ -386,7 +387,7 @@ public void WinFormsButtonClickInvokesRssCallbackOnTheOwningStaThread()
using var application = PdVmWinFormsApplication.Attach(program, host);
_ = PdVmExecution.Run(program, host);
using var watchdog = new System.Threading.Timer(
- _ => ExitWindowsFormsApplication(),
+ _ => application.CloseMainForm(),
null,
TimeSpan.FromSeconds(3),
Timeout.InfiniteTimeSpan);
@@ -1170,7 +1171,7 @@ public void WinFormsTimerInvokesRssCallableOnTheOwningStaThread()
{
try
{
- _ = PdVmDotNetHost.InitializeWindowsFormsApplication();
+ _ = WinFormsTestSupport.Initialize();
using var program = Assert.IsAssignableFrom(
PdVmAssemblyLoader.CreateProgram(Assembly.Load(File.ReadAllBytes(output))));
var host = PdVmDefaultHost.CreateConsoleHost();
@@ -1179,7 +1180,7 @@ public void WinFormsTimerInvokesRssCallableOnTheOwningStaThread()
using var application = PdVmWinFormsApplication.Attach(program, host);
_ = PdVmExecution.Run(program, host);
using var watchdog = new System.Threading.Timer(
- _ => ExitWindowsFormsApplication(),
+ _ => application.CloseMainForm(),
null,
TimeSpan.FromSeconds(3),
Timeout.InfiniteTimeSpan);
@@ -1254,18 +1255,6 @@ private static PdVmProgramMetadata GetProgramMetadata(IPdVmProgram program)
return Assert.IsType(metadataField.GetValue(program));
}
- private static void ExitWindowsFormsApplication() =>
- Type.GetType(
- "System.Windows.Forms.Application, System.Windows.Forms",
- throwOnError: true)!
- .GetMethod(
- "Exit",
- BindingFlags.Public | BindingFlags.Static,
- binder: null,
- types: Type.EmptyTypes,
- modifiers: null)!
- .Invoke(null, null);
-
private static async Task WaitUntilAsync(Func condition)
{
var deadline = DateTime.UtcNow + TimeSpan.FromSeconds(5);
diff --git a/PdVm.Tests/WinFormsTestSupport.cs b/PdVm.Tests/WinFormsTestSupport.cs
new file mode 100644
index 00000000..f77c62aa
--- /dev/null
+++ b/PdVm.Tests/WinFormsTestSupport.cs
@@ -0,0 +1,165 @@
+using System.Reflection;
+using PdVm.Runtime;
+
+namespace PdVm.Tests;
+
+///
+/// Windows Forms keeps process-wide state: visual styles and DPI awareness can only be
+/// configured before the first window handle exists, and Application.Exit terminates
+/// every message loop in the process. Tests that create forms therefore join one
+/// non-parallel collection and share a single initialization.
+///
+[CollectionDefinition(Name, DisableParallelization = true)]
+public sealed class WinFormsCollection
+{
+ public const string Name = "windows-forms";
+}
+
+///
+/// Process-wide Windows Forms setup shared by the UI tests.
+///
+internal static class WinFormsTestSupport
+{
+ private static readonly object Gate = new();
+ private static bool _initialized;
+ private static bool _available;
+ private static Exception? _failure;
+
+ ///
+ /// Initializes Windows Forms once per process and reports whether it is usable.
+ /// The first call also pumps a throwaway message loop so that one-time toolkit
+ /// initialization (assembly load, GDI+/font/theme setup, first window creation)
+ /// does not land inside a test's own deadline.
+ ///
+ public static bool Initialize()
+ {
+ lock (Gate)
+ {
+ if (!_initialized)
+ {
+ _initialized = true;
+ try
+ {
+ _available = PdVmDotNetHost.InitializeWindowsFormsApplication();
+ if (_available)
+ {
+ PumpThrowawayMessageLoop();
+ }
+ }
+ catch (Exception exception)
+ {
+ _failure = exception;
+ }
+ }
+
+ if (_failure is not null)
+ {
+ throw new InvalidOperationException("Windows Forms initialization failed", _failure);
+ }
+
+ return _available;
+ }
+ }
+
+ ///
+ /// Closes a form on its own UI thread without touching other message loops in the process.
+ ///
+ public static bool CloseForm(object form)
+ {
+ ArgumentNullException.ThrowIfNull(form);
+ var close = form.GetType().GetMethod(
+ "Close",
+ BindingFlags.Public | BindingFlags.Instance,
+ binder: null,
+ types: Type.EmptyTypes,
+ modifiers: null);
+ if (close is null)
+ {
+ return false;
+ }
+
+ var beginInvoke = form.GetType().GetMethod(
+ "BeginInvoke",
+ BindingFlags.Public | BindingFlags.Instance,
+ binder: null,
+ types: [typeof(Delegate)],
+ modifiers: null);
+ if (beginInvoke is null)
+ {
+ return false;
+ }
+
+ Action action = () => close.Invoke(form, null);
+ try
+ {
+ _ = beginInvoke.Invoke(form, [action]);
+ return true;
+ }
+ catch (TargetInvocationException exception)
+ when (exception.InnerException is InvalidOperationException or ObjectDisposedException)
+ {
+ // The window handle is already gone; the owning loop has nothing left to close.
+ return false;
+ }
+ }
+
+ private static void PumpThrowawayMessageLoop()
+ {
+ if (!OperatingSystem.IsWindows())
+ {
+ return;
+ }
+
+ Exception? failure = null;
+ var thread = new Thread(() =>
+ {
+ try
+ {
+ RunThrowawayMessageLoop();
+ }
+ catch (Exception exception)
+ {
+ failure = exception;
+ }
+ })
+ {
+ IsBackground = true,
+ };
+ thread.SetApartmentState(ApartmentState.STA);
+ thread.Start();
+ if (!thread.Join(TimeSpan.FromSeconds(30)))
+ {
+ throw new InvalidOperationException("the Windows Forms warm-up message loop did not exit");
+ }
+
+ if (failure is not null)
+ {
+ throw new InvalidOperationException("the Windows Forms warm-up message loop failed", failure);
+ }
+ }
+
+ private static void RunThrowawayMessageLoop()
+ {
+ var formType = Type.GetType(
+ "System.Windows.Forms.Form, System.Windows.Forms",
+ throwOnError: true)!;
+ var application = Type.GetType(
+ "System.Windows.Forms.Application, System.Windows.Forms",
+ throwOnError: true)!;
+ var form = Activator.CreateInstance(formType)!;
+ formType.GetProperty("ShowInTaskbar")?.SetValue(form, false);
+ using var timer = new System.Threading.Timer(
+ _ => CloseForm(form),
+ null,
+ TimeSpan.FromMilliseconds(100),
+ Timeout.InfiniteTimeSpan);
+ var run = application.GetMethod(
+ "Run",
+ BindingFlags.Public | BindingFlags.Static,
+ binder: null,
+ types: [formType],
+ modifiers: null)!;
+ _ = run.Invoke(null, [form]);
+ (form as IDisposable)?.Dispose();
+ }
+}