SystemTrayMenu/Utilities/AppRestart.cs

78 lines
2 KiB
C#
Raw Normal View History

// <copyright file="AppRestart.cs" company="PlaceholderCompany">
// Copyright (c) PlaceholderCompany. All rights reserved.
// </copyright>
namespace SystemTrayMenu.Utilities
{
using System;
using System.ComponentModel;
using System.Diagnostics;
using System.Runtime.CompilerServices;
using System.Windows;
internal class AppRestart
{
2023-04-17 09:27:27 +12:00
public static event Action? BeforeRestarting;
internal static void ByThreadException()
{
Restart(GetCurrentMethod());
}
internal static void ByAppContextMenu()
{
Restart(GetCurrentMethod());
}
internal static void ByConfigChange()
{
Restart(GetCurrentMethod());
}
internal static void ByMenuButton()
{
Restart(GetCurrentMethod());
}
2023-04-17 09:27:27 +12:00
private static void Restart(string? reason)
{
BeforeRestarting?.Invoke();
2023-04-17 09:27:27 +12:00
Log.Info($"Restart by '{reason ?? "unkown"}'");
Log.Close();
using (Process p = new())
{
2023-04-17 09:27:27 +12:00
string? fileName = System.Environment.ProcessPath;
if (string.IsNullOrEmpty(fileName))
{
2023-04-17 09:27:27 +12:00
Log.Warn("Restart failed", new());
}
2023-04-17 09:27:27 +12:00
else
{
2023-04-17 09:27:27 +12:00
p.StartInfo = new ProcessStartInfo(fileName);
try
{
p.Start();
}
catch (Win32Exception ex)
{
Log.Warn("Restart failed", ex);
}
}
}
Application.Current.Shutdown();
}
[MethodImpl(MethodImplOptions.NoInlining)]
2023-04-17 09:27:27 +12:00
private static string? GetCurrentMethod()
{
StackTrace st = new();
2023-04-17 09:27:27 +12:00
StackFrame? sf = st.GetFrame(1);
2023-04-17 09:27:27 +12:00
return sf?.GetMethod()?.Name;
}
}
}