Files
laatzen/Common/Ui/Common.UI/App.xaml.cs
T

95 lines
2.9 KiB
C#

namespace Common.UI
{
using Common.UI.Infrastructure;
using Common.UI.Infrastructure.Contracts;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Diagnostics;
using System.Windows;
using System.Windows.Controls;
public partial class App : Application
{
internal static void InvokeAsync(Action action)
=> Current.Dispatcher.InvokeAsync(action);
protected override void OnStartup(StartupEventArgs e)
{
if (!this.ShutdownRunningInstance())
{
var mainWindow = new MainWindow();
var args = e.Args;
if (args?.Length > 0)
{
var source = $"Pages/{args[0]}.xaml";
var sourceUri = new Uri(source, UriKind.RelativeOrAbsolute);
if (args?.Length > 1)
{
mainWindow.Navigated += (_, eargs) =>
{
if (eargs.Content is Page page)
{
if (int.TryParse($"{args[1]}", out var sharedId))
{
page.Tag = sharedId;
}
}
};
}
mainWindow.NavigationService.Navigate(sourceUri, args[1]);
}
AppHost.ConfigureServices(services =>
{
services.AddScoped<INavigation, MainWindow>(_ => mainWindow);
});
Current.Exit += (_1, _2) =>
{
ViewModel.ApplicationExit();
};
this.MainWindow = mainWindow;
this.MainWindow.Show();
}
}
private bool ShutdownRunningInstance()
{
var currentProcess = Process.GetCurrentProcess();
var shutdownCalled = false;
foreach (var process in Process.GetProcessesByName(currentProcess.ProcessName))
{
if (process.Id != currentProcess.Id && process.MainModule.FileName == currentProcess.MainModule.FileName)
{
var windowHandle = process.MainWindowHandle;
if (windowHandle != IntPtr.Zero)
{
if (User32DllImports.IsIconic(windowHandle))
{
User32DllImports.ShowWindow(windowHandle, WindowCommands.Restore);
}
User32DllImports.SetForegroundWindow(windowHandle);
this.Shutdown();
shutdownCalled = true;
break;
}
}
}
return shutdownCalled;
}
}
}