Multiple Windows (Desktop)

Multiple Windows aren't supported on mobile and tablet currently.

By default, Wisej.NET Hybrid desktop apps support multiple instances.

Handling New Instances

When opening a new instance of a Wisej.NET Hybrid application on Windows, you may run into an exception from the embedded web server that the port is already in use. Here's how you can ensure an open port is used for each new instance:

Inside of the Hybrid Client's Startup.cs file:

namespace HybridClient
{
	public static class Startup
	{
		public static MauiApp Main()
		{
			// find a url to run the application on.
			var localUrl = WisejExtensions.GetLocalUrl();
	
			var builder = MauiApp.CreateBuilder();
			builder
				.UseMauiApp<App>()
	
				 // Uncomment and replace with Offline startup Type to use embedded web server.
				 .UseWisejOffline<OfflineStartup>(localUrl)
	
				.UseWisejHybrid((config) =>
				{
					// Provide the startup URL for the Hybrid WebView.
					config.StartupUrl = localUrl;
				});
	
			return builder.Build();
		}
	}
}

Inside of the Local Hybrid project's OfflineStartup.cs file:

public static string Main(CancellationToken token, object[] args)
{
	var url = (string)args.FirstOrDefault();
	var server = new WebServer(url);
	server.WithWisej();
	server.Run(token);

	return url;
}

Limit to One Instance

If you'd like to only allow the user to have one open window at any given time, add the following code to the Hybrid Client's Platforms/Windows/App.xaml.cs file:

// To learn more about WinUI, the WinUI project structure,
// and more about our project templates, see: http://aka.ms/winui-project-info.

/// <summary>
/// Provides application-specific behavior to supplement the default Application class.
/// </summary>
public partial class App : HybridWinUIApplication
{
	/// <summary>
	/// Initializes the singleton application object.  This is the first line of authored code
	/// executed, and as such is the logical equivalent of main() or WinMain().
	/// </summary>
	public App()
	{
		this.InitializeComponent();
	}

	protected override MauiApp CreateMauiApp() => Startup.Main();

	static Mutex? mutex;

	protected override void OnLaunched(LaunchActivatedEventArgs args)
	{
		if (!IsSingleInstance())
		{
			Process.GetCurrentProcess().Kill();
		}
		else
		{
			base.OnLaunched(args);
		}
	}

	static bool IsSingleInstance()
	{
		var applicationId = AppInfo.Current.PackageName;
		mutex = new Mutex(false, applicationId);
		GC.KeepAlive(mutex);

		try
		{
			return mutex.WaitOne(0, false);
		}
		catch (AbandonedMutexException)
		{
			mutex.ReleaseMutex();
			return mutex.WaitOne(0, false);
		}
	}
}

Last updated