I am currently writing a WPF application which does command-line argument handling in App.xaml.cs (which is necessary because the Startup event seems to be the recommended w
I did this a little differently to avoid having to set the StartupUri and ShutdownMode properties. First edit the App.xaml file and replace StartupUri with Startup:
Then add Application_Startup to the code along with OnExit:
public partial class App : Application
{
private volatile static Mutex s_mutex;
private void Application_Startup(object sender, StartupEventArgs e)
{
s_mutex = new Mutex(true, @"Global\MenuMutex", out bool grantedOwnership);
if (!grantedOwnership)
{
MessageBox.Show($"Another instance is already running!", "Error", MessageBoxButton.OK, MessageBoxImage.Exclamation);
Current.Shutdown();
}
else
new MainWindow().Show();
}
protected override void OnExit(ExitEventArgs e)
{
s_mutex?.ReleaseMutex();
s_mutex?.Dispose();
s_mutex = null;
base.OnExit(e);
}