From 8b764b1fe865e705d33aa5462a3b885d8ed4fc10 Mon Sep 17 00:00:00 2001 From: Cameron White Date: Sat, 13 May 2023 16:24:30 -0400 Subject: [PATCH] Set the main thread's apartment state when initializing GDK This seems to be the logical place to do it since the startup error comes from GDK, and this also ensures it's done automatically without any extra steps to document for users. This is wrapped in a check for whether we're running on Windows, to avoid warnings from the `SupportedOSPlatform` attribute on `SetApartmentState()` Fixes: #864 --- src/Libs/Gdk-4.0/Public/Module.cs | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-) diff --git a/src/Libs/Gdk-4.0/Public/Module.cs b/src/Libs/Gdk-4.0/Public/Module.cs index dfefdb49d..1c095158c 100644 --- a/src/Libs/Gdk-4.0/Public/Module.cs +++ b/src/Libs/Gdk-4.0/Public/Module.cs @@ -1,4 +1,7 @@ -namespace Gdk; +using System.Runtime.InteropServices; +using System.Threading; + +namespace Gdk; public class Module { @@ -14,6 +17,15 @@ public static void Initialize() Internal.ImportResolver.RegisterAsDllImportResolver(); Internal.TypeRegistration.RegisterTypes(); + // On Windows, GDK requires the main thread's apartment state to be STA. + if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) + { + // In order to successfully switch from MTA to STA, it is necessary + // to first set it to Unknown. + Thread.CurrentThread.SetApartmentState(ApartmentState.Unknown); + Thread.CurrentThread.SetApartmentState(ApartmentState.STA); + } + IsInitialized = true; } }