/*
* App.xaml.cs - Better-Seewo 管理器应用程序逻辑
* 负责全局异常处理和主题切换功能
* 作者:雾启工作室
*/
using System;
using System.IO;
using System.Windows;
using System.Windows.Resources;
namespace Better_Seewo.Manager
{
///
/// App 的交互逻辑
///
public partial class App : Application
{
///
/// 标记当前是否为深色主题
///
private static bool _isDarkTheme = true;
///
/// 获取当前是否为深色主题
///
public static bool IsDarkTheme => _isDarkTheme;
///
/// 应用程序启动时初始化全局异常处理
///
protected override void OnStartup(StartupEventArgs e)
{
// 注册全局未处理异常事件
DispatcherUnhandledException += App_DispatcherUnhandledException;
AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
base.OnStartup(e);
}
///
/// UI线程未处理异常捕获,防止程序崩溃并提示用户
///
private void App_DispatcherUnhandledException(object sender, System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e)
{
// 记录异常信息到日志文件
LogError(e.Exception);
// 标记异常已处理,防止程序崩溃
e.Handled = true;
// 弹出友好提示
MessageBox.Show(
$"发生未预期的错误:\n{e.Exception.Message}\n\n详细信息已记录到日志。",
"Better-Seewo 管理器",
MessageBoxButton.OK,
MessageBoxImage.Warning
);
}
///
/// 非UI线程未处理异常捕获
///
private void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
{
if (e.ExceptionObject is Exception ex)
{
LogError(ex);
}
}
///
/// 将错误信息记录到日志文件
///
private static void LogError(Exception ex)
{
try
{
// 日志文件存放在可执行文件同目录下
string logDir = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Logs");
Directory.CreateDirectory(logDir);
string logFile = Path.Combine(logDir, $"error_{DateTime.Now:yyyyMMdd}.log");
string logContent = $"[{DateTime.Now:yyyy-MM-dd HH:mm:ss}] {ex}\n\n";
File.AppendAllText(logFile, logContent);
}
catch
{
// 日志写入失败时静默处理
}
}
///
/// 切换深色/浅色主题
///
/// true为深色主题,false为浅色主题
public static void SwitchTheme(bool isDark)
{
_isDarkTheme = isDark;
// 获取当前应用程序实例
var app = Current;
if (app == null) return;
// 清除所有现有资源字典
app.Resources.MergedDictionaries.Clear();
// 获取应用程序所在目录
string themeDir = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Themes");
// 根据选择加载对应主题
string themeFile = isDark ? "DarkTheme.xaml" : "LightTheme.xaml";
string themePath = Path.Combine(themeDir, themeFile);
// 加载主题资源字典
var themeDict = new ResourceDictionary
{
Source = new Uri(themePath, UriKind.Absolute)
};
// 将主题资源添加到合并字典中
app.Resources.MergedDictionaries.Add(themeDict);
}
}
}