Files
Sleep-Multi-functionality/App.xaml.cs

95 lines
3.3 KiB
C#
Raw Normal View History

2026-05-04 14:46:58 +08:00
using System;
2026-05-07 16:51:45 +08:00
using System.Configuration;
2026-05-04 14:46:58 +08:00
using System.Diagnostics;
using System.IO;
using System.Security.Principal;
using System.Windows;
namespace ShanghaiEnvironmentalTechnology
{
public partial class App : Application
{
public App()
{
// 捕获UI线程异常
DispatcherUnhandledException += App_DispatcherUnhandledException;
// 捕获非UI线程异常
AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
// 捕获任务线程异常
System.Threading.Tasks.TaskScheduler.UnobservedTaskException += TaskScheduler_UnobservedTaskException;
}
private void App_DispatcherUnhandledException(object sender, System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e)
{
LogError(e.Exception, "UI线程异常");
e.Handled = true; // 标记为已处理,避免崩溃(仅用于调试)
}
private void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
{
if (e.ExceptionObject is Exception ex)
LogError(ex, "应用域未处理异常");
}
private void TaskScheduler_UnobservedTaskException(object sender, System.Threading.Tasks.UnobservedTaskExceptionEventArgs e)
{
LogError(e.Exception, "任务线程异常");
e.SetObserved();
}
private void LogError(Exception ex, string type)
{
string logPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "error.log");
string logContent = $"[{DateTime.Now:yyyy-MM-dd HH:mm:ss}] {type}\n{ex.ToString()}\n\n";
File.AppendAllText(logPath, logContent);
MessageBox.Show($"发生错误,详情已记录到 {logPath}", "错误");
}
protected override void OnStartup(StartupEventArgs e)
{
base.OnStartup(e);
if (!IsRunAsAdmin())
{
RestartAsAdmin();
Shutdown();
}
2026-05-07 16:51:45 +08:00
// 加载保存的语言
string savedLanguage = ConfigurationManager.AppSettings["Language"] ?? "zh-CN";
var resourceDict = new ResourceDictionary
{
Source = new Uri($"/Resources/Strings.{savedLanguage}.xaml", UriKind.Relative)
};
Current.Resources.MergedDictionaries.Clear();
Current.Resources.MergedDictionaries.Add(resourceDict);
2026-05-04 14:46:58 +08:00
}
private bool IsRunAsAdmin()
{
WindowsIdentity identity = WindowsIdentity.GetCurrent();
WindowsPrincipal principal = new WindowsPrincipal(identity);
return principal.IsInRole(WindowsBuiltInRole.Administrator);
}
private void RestartAsAdmin()
{
ProcessStartInfo startInfo = new ProcessStartInfo();
startInfo.UseShellExecute = true;
startInfo.WorkingDirectory = Environment.CurrentDirectory;
startInfo.FileName = Process.GetCurrentProcess().MainModule.FileName;
startInfo.Verb = "runas"; // Run as administrator
try
{
Process.Start(startInfo);
}
catch (Exception ex)
{
MessageBox.Show("Error: " + ex.Message);
}
}
}
}