using System;
using System.IO;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Threading;
using System.Windows;
namespace AnotherReplayReader
{
///
/// App.xaml 的交互逻辑
///
public partial class App : Application
{
private int _isInException = 0;
public const string Version = "0.7";
public const string Name = "自动录像机";
public const string NameWithVersion = Name + " v" + Version;
private static readonly Lazy _libsFolder = new(GetLibraryFolder, LazyThreadSafetyMode.PublicationOnly);
public static string LibsFolder => _libsFolder.Value;
public App()
{
static Assembly? LoadFromLibsFolder(object sender, ResolveEventArgs args)
{
var assemblyPath = Path.Combine(LibsFolder, new AssemblyName(args.Name).Name + ".dll");
return File.Exists(assemblyPath)
? Assembly.LoadFrom(assemblyPath)
: null;
}
AppDomain.CurrentDomain.AssemblyResolve += new ResolveEventHandler(LoadFromLibsFolder);
AppDomain.CurrentDomain.UnhandledException += (sender, eventArgs) =>
{
if (Interlocked.Increment(ref _isInException) > 1)
{
return;
}
Dispatcher.Invoke(() =>
{
const string message = "哎呀呀,出现了一些无法处理的问题,只能退出了。要不要尝试保存一下日志文件呢?";
var choice = MessageBox.Show($"{message}\r\n{eventArgs.ExceptionObject}", Name, MessageBoxButton.YesNo);
if (choice == MessageBoxResult.Yes)
{
Debug.Instance.RequestSave();
}
});
};
}
private static string GetLibraryFolder() => Path.Combine(GetExecutableFolder(), nameof(AnotherReplayReader) + "Data");
private static string GetExecutableFolder()
{
char[]? buffer = null;
uint result;
do
{
buffer = new char[(buffer?.Length ?? 128) * 2];
result = GetModuleFileNameW(IntPtr.Zero, buffer, buffer.Length);
if (result is 0)
{
throw new Exception("Failed to retrieve executable name");
}
}
while (result >= buffer.Length);
return Path.GetDirectoryName(new(buffer, 0, Array.IndexOf(buffer, '\0')));
}
[DllImport("Kernel32.dll", CallingConvention = CallingConvention.Winapi, CharSet = CharSet.Unicode, ExactSpelling = true, SetLastError = true)]
private static extern uint GetModuleFileNameW(IntPtr module, char[] fileName, int size);
}
}