I need to write a .NET6 library that allows some features only when it's used with a WinForms or WPF app (so no console app, no web service, etc...).
I already checked some other posts like this but hits like Environment.UserInteractive
or System.Diagnostics.Process.GetCurrentProcess().MainWindowHandle == IntPtr.Zero
seem not to work.
Prerequisites are:
- it must be cross-platform
- it can't reference System.Windows.Forms or PresentationFramework
- I can't use methods that import Windows library like
[DllImport("kernel32.dll")]
- I can't use a static method that is called by the application that uses my library
Listed below is the code I'm currently testing. It seems to work, but I'm wondering whether there is a more efficient and reliable way to reach my goal.
static bool? _isWindowsGuiApp = null;
static bool IsWindowsGuiApp()
{
if (!_isWindowsGuiApp.HasValue)
{
_isWindowsGuiApp = false;
var entryAssembly = Assembly.GetEntryAssembly();
if (entryAssembly != null)
{
string[] wpfAssemblies = { "PresentationFramework", "PresentationCore", "WindowsBase" };
string[] winFormsAssemblies = { "System.Windows.Forms" };
var referencedAssemblies = entryAssembly.GetReferencedAssemblies();
foreach (var assemblyName in referencedAssemblies)
{
if (wpfAssemblies.Contains(assemblyName.Name))
{
_isWindowsGuiApp = true; // WPF
break;
}
if (winFormsAssemblies.Contains(assemblyName.Name))
{
_isWindowsGuiApp = true; // WinForms
break;
}
}
}
}
return _isWindowsGuiApp.Value;
}