alielie
2025-08-25 c4a3f8db90530a727ffab77c3bb5bb7d782792bf
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
using HMI.Core.Setting;
using HMI.Core.Util;
using HMI.UI.Util;
using log4net;
using Microsoft.Win32;
using Panuon.WPF.UI;
using System;
using System.Diagnostics;
using System.IO;
using System.Management;
using System.Reflection;
using System.Threading;
using System.Windows;
using WPFProject.Utils;
 
namespace WPFProject
{
    /// <summary>
    /// App.xaml 的交互逻辑
    /// </summary>
    public partial class App : Application
    {
        private ILog log;
        private LogCleanner logCleanner;
        public App()
        {
            log = LogManager.GetLogger("APP");
            AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
        }
 
        private void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            var ex = e.ExceptionObject as Exception;
            log.Error("UnhandledException.", ex);
            MsgBoxHelper.ErrorMessage(Current.MainWindow, this.lang("App.AppUnhandledException", ex.Message),
                    this.lang("App.Error"), MessageBoxButton.OK,
                    MessageBoxIcon.Error, DefaultButton.YesOK, 5);
        }
 
        public static Process GetProcess()
        {
            Process cur = Process.GetCurrentProcess();
            string exePath = Assembly.GetExecutingAssembly().Location;
            string query = $"SELECT ProcessId FROM Win32_Process WHERE ExecutablePath = '{exePath.Replace("\\", "\\\\")}'";
            using (var searcher = new ManagementObjectSearcher(query))
            {
                foreach (var obj in searcher.Get())
                {
                    int processId = Convert.ToInt32(obj["ProcessId"]);
                    if (processId != cur.Id)
                    {
                        return Process.GetProcessById(processId);
                    }
                }
            }
            return null;
        }
 
        /// <summary>
        /// 启动后往注册表写点东西
        /// </summary>
        private void WriteRegister()
        {
            string Company = "JingCe", Program = "HMI";
            try
            {
                string registryPath = @$"SOFTWARE\{Company}\{Program}";
 
                using RegistryKey key = Registry.CurrentUser.CreateSubKey(registryPath, true)
                    ?? throw new Exception("无法创建或打开注册表键");
                string path = AppDomain.CurrentDomain.BaseDirectory;
                key.SetValue("Location", path, RegistryValueKind.String);
            }
            catch (Exception ex)
            {
                log.Error("Write Register Failed.", ex);
            }
        }
 
        private void DoUpdateAction()
        {
            using (SqliteHelper helper = new SqliteHelper(PathHelper.DatabasePath))
            {
                if (!helper.HasData("SELECT 1 FROM pragma_table_info('user') WHERE name = 'code';"))
                {
                    helper.ExecuteSql("ALTER TABLE user ADD code TEXT;");
                }
            }
        }
 
        private static Mutex mutex;
        private void Application_Startup(object sender, StartupEventArgs e)
        {
            var process = GetProcess();
 
            mutex = new Mutex(true, "TestPlatform_OnlyRun_CRNS");
            if (mutex.WaitOne(0, false))//&& process == null
            {
                WriteRegister();
                try
                {
                    DoUpdateAction();
                }
                catch (Exception ex) {
                    log.Error("Update Failed.", ex);
                }
 
                logCleanner = new LogCleanner();
                AppDomain.CurrentDomain.AssemblyResolve += CurrentDomain_AssemblyResolve;
                LoggerHelper.Register(new CommonLogger());
                LangUtil.Load();
                SystemSetting.SystemSettingChanged += SystemSetting_SystemSettingChanged;
                ToastHelper.Register(new MainToastHandler());
                //LoadingWindow window = new LoadingWindow();
                Login window = new Login();
                window.Show();
            }
            else
            {
                MessageBox.Show("程序已经在运行!", "提示");
                this.Shutdown();
            }
        }
 
        private Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args)
        {
            // 获取请求加载的程序集名称
            string assemblyName = new AssemblyName(args.Name).Name;
 
            string[] dirs = new string[] { "3rds", "Libs" };
 
            foreach (string dir in dirs)
            {
                string dllPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, dir, $"{assemblyName}.dll");
                if (File.Exists(dllPath))
                {
                    // 如果依赖 DLL 存在,则加载并返回它
                    return Assembly.LoadFrom(dllPath);
                }
            }
            // 否则返回 null
            return null;
        }
 
        private void SystemSetting_SystemSettingChanged(object sender, SystemSetting e)
        {
            LangUtil.LoadLang();
        }
    }
}