83 lines
2.9 KiB
C#
83 lines
2.9 KiB
C#
using System;
|
||
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();
|
||
}
|
||
}
|
||
|
||
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);
|
||
}
|
||
}
|
||
}
|
||
} |