schangxiang@126.com
2025-11-04 ca398287db3f5ea01f03aac4a85edb13b28100a6
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
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
using DataEntity.Share;
using HxEnum;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Threading;
using XCommon;
using XCommon.Log;
using XCommon.MySql;
using XImagingXhandler.XDAL;
 
namespace XHandler
{
    /// <summary>
    /// App.xaml 的交互逻辑
    /// </summary>
    public partial class App : Application
    {
        /// 该函数设置由不同线程产生的窗口的显示状态
        /// </summary>
        /// <param name="hWnd">窗口句柄</param>
        /// <param name="cmdShow">指定窗口如何显示。查看允许值列表,请查阅ShowWlndow函数的说明部分</param>
        /// <returns>如果函数原来可见,返回值为非零;如果函数原来被隐藏,返回值为零</returns>
        [DllImport("User32.dll")]
        private static extern bool ShowWindowAsync(IntPtr hWnd, int cmdShow);
 
        /// <summary>
        ///  该函数将创建指定窗口的线程设置到前台,并且激活该窗口。键盘输入转向该窗口,并为用户改各种可视的记号。
        ///  系统给创建前台窗口的线程分配的权限稍高于其他线程。 
        /// </summary>
        /// <param name="hWnd">将被激活并被调入前台的窗口句柄</param>
        /// <returns>如果窗口设入了前台,返回值为非零;如果窗口未被设入前台,返回值为零</returns>
        [DllImport("User32.dll")]
        private static extern bool SetForegroundWindow(IntPtr hWnd);
        private const int SW_MAXIMIZE = 3;
 
        private static void HandleRunningInstance(Process instance)
        {
            ShowWindowAsync(instance.MainWindowHandle, SW_MAXIMIZE);//显示
            SetForegroundWindow(instance.MainWindowHandle);//当到最前端
        }
        private static Process RuningInstance()
        {
            Process currentProcess = Process.GetCurrentProcess();
            Process[] Processes = Process.GetProcessesByName(currentProcess.ProcessName);
            foreach (Process process in Processes)
            {
                if (process.Id != currentProcess.Id)
                {
                    if (Assembly.GetExecutingAssembly().Location.Replace("/", "\\") == currentProcess.MainModule.FileName)
                    {
                        return process;
                    }
                }
            }
            return null;
        }
        protected override void OnStartup(StartupEventArgs e)
        {
            try
            {
                LoggerHelper.InitialILog();
                LoggerRunHelper.InitialILog();
                LoggerSocketHelper.InitialILog();
 
                Process process = RuningInstance();
                if (process != null)
                {
                    LoggerHelper.InfoLog("应用程序已经在运行中。。。");
                    HandleRunningInstance(process);
                    System.Threading.Thread.Sleep(1000);
                    System.Environment.Exit(1);
                }
 
                if (!MySqlUtity.ConnectTestW(MySqlUtity.GetConnection()))
                {
                    MessageBox.Show("数据库连接失败,请检查!");
                    System.Environment.Exit(1);
                }
 
                LoggerHelper.InfoLog("应用程序启动。。。");
 
                // 获取当前软件信息
                LoggerHelper.InfoLog("1");
                SoftwareInformation softwareInfo = SoftwareInformationDB.GetSoftwareInformationDataFromdb(EnumManagement.GetEnumValue(IsAvailableEnum.Yes));
                LoggerHelper.InfoLog("2");
                Shared.SoftwareInformation = softwareInfo;
                LoggerHelper.InfoLog("3");
                // 获取当前设备臂信息
                if(softwareInfo == null) { return; }
                List<DeviceArm> deviceArmList = DeviceArmDB.GetDeviceArmFromdb(softwareInfo.software_information_id);
                LoggerHelper.InfoLog("4");
                Shared.DeviceArmList = deviceArmList;
                LoggerHelper.InfoLog("5");
 
                // 夹爪机械臂ID
                var gripper = deviceArmList.FirstOrDefault(it=>it.arm_type == EnumManagement.GetEnumValue(ArmTypeEnum.Gripper));
                if (gripper == null)
                {
                    //MessageBox.Show("夹爪机械臂获取失败,请检查!");
                    //System.Environment.Exit(1);
                    //可能设备就没有夹爪
                }
                else
                {
                    Shared.GripperArmId = gripper.device_arm_id;
                }
 
                // 通道配置
                var channel = deviceArmList.FirstOrDefault(it => it.arm_type == EnumManagement.GetEnumValue(ArmTypeEnum.Channel));
                if (channel == null)
                {
                    MessageBox.Show("通道获取失败,请检查!");
                    System.Environment.Exit(1);
                }
 
                if (channel.channels == 96)
                {
                    Shared.ChannelCount = 96;
                }
                else
                {
                    Shared.ChanelArmId = channel.device_arm_id;
                    string[] strArmProperty = channel.device_arm_property.Trim().Split(',');
                    if (strArmProperty.Length > 0&& strArmProperty[0]!="")
                    {
                        if (channel.channels >= 1 && strArmProperty.Length == 1)
                        {
                            Shared.ChannelsId = Array.ConvertAll<string, int>(strArmProperty, s => int.Parse(s));
                            Shared.ChannelCount = channel.channels;
                        }
                        else
                        {
                            Array.ConvertAll<string, int>(strArmProperty, s => int.Parse(s));
                            Shared.ChannelsId = Array.ConvertAll<string, int>(strArmProperty, s => int.Parse(s));
                            Shared.ChannelCount = Shared.ChannelsId.Length;
                        }
                    }
                    if (Shared.ChannelCount == 0)
                    {
                        MessageBox.Show("已设置通道数量为0,请检查!");
                        System.Environment.Exit(1);
                    }
                }
 
                #region 获取配置参数
                if (!ComUtility.GetConfigParams())
                {
                    MessageBox.Show("获取配置参数失败,请检查!");
                    System.Environment.Exit(1);
                }
                #endregion
 
                FrameworkCompatibilityPreferences.KeepTextBoxDisplaySynchronizedWithTextProperty = false;
                base.OnStartup(e);
            }
            catch (Exception ex)
            {
                LoggerHelper.ErrorLog("ERROR:", ex);
            }
        }
 
        public App()
        {
            Startup += App_Startup;
            Exit += App_Exit;
        }
 
        private void App_Exit(object sender, ExitEventArgs e)
        {
            LoggerHelper.InfoLog("应用程序退出。。。");
            LoggerHelper.ShutDownLogger();
            LoggerRunHelper.ShutDownLogger();
        }
 
        private void App_Startup(object sender, StartupEventArgs e)
        {
            //UI线程未捕获异常处理事件
            DispatcherUnhandledException += App_DispatcherUnhandledException;
            //Task线程内未捕获异常处理事件
            TaskScheduler.UnobservedTaskException += TaskScheduler_UnobservedTaskException;
            //非UI线程未捕获异常处理事件
            AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
        }
 
        /// <summary>
        /// UI线程未捕获异常处理函数
        /// </summary>
        private void App_DispatcherUnhandledException(object sender, DispatcherUnhandledExceptionEventArgs e)
        {
            try
            {
                LoggerHelper.ErrorLog(e.ToString());
                e.Handled = true;
                string msg = ExceptionToString(e.Exception, "UI线程");
                MessageBox.Show(msg, "系统错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
            catch (Exception ex)
            {
                LoggerHelper.ErrorLog("ERROR:", ex);
                string msg = ExceptionToString(ex, "UI线程 处理函数");
                MessageBox.Show(msg, "系统错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }
 
        /// <summary>
        /// Task线程内未捕获异常处理函数
        /// </summary>
        private void TaskScheduler_UnobservedTaskException(object sender, UnobservedTaskExceptionEventArgs e)
        {
            try
            {
                LoggerHelper.ErrorLog(e.ToString());
                string msg = ExceptionToString(e.Exception, "Task线程");
                MessageBox.Show(msg, "系统错误", MessageBoxButton.OK, MessageBoxImage.Error);
                e.SetObserved();//设置该异常已察觉(这样处理后就不会引起程序崩溃)
            }
            catch (Exception ex)
            {
                LoggerHelper.ErrorLog("ERROR:", ex);
                string msg = ExceptionToString(ex, "Task线程 处理函数");
                MessageBox.Show(msg, "系统错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }
        /// <summary>
        /// 非UI线程未捕获异常处理函数
        /// </summary>
        private void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            try
            {
                LoggerHelper.ErrorLog(e.ToString());
                string msg;
                if (e.ExceptionObject is Exception ex)
                {
                    msg = ExceptionToString(ex, "非UI线程");
                }
                else
                {
                    msg = $"发生了一个错误!信息:{e.ExceptionObject}";
                }
                MessageBox.Show(msg, "系统错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
            catch (Exception ex)
            {
                LoggerHelper.ErrorLog("ERROR:", ex);
                string msg = ExceptionToString(ex, "非UI线程 处理函数");
                MessageBox.Show(msg, "系统错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }
 
        /// <summary>
        /// 提取异常信息
        /// </summary>
        private static string ExceptionToString(Exception ex, string info)
        {
            LoggerHelper.ErrorLog("ERROR", ex);
 
            StringBuilder str = new StringBuilder($"{DateTime.Now}, {info}发生了一个错误!{Environment.NewLine}");
            if (ex.InnerException == null)
            {
                str.Append($"[对象名称]:{ex.Source}{Environment.NewLine}");
                str.Append($"[异常类型]:{ex.GetType().Name}{Environment.NewLine}");
                str.Append($"[详细信息]:{ex.Message}{Environment.NewLine}");
                str.Append($"[堆栈调用]:{ex.StackTrace}");
            }
            else
            {
                str.Append($"[对象名称]:{ex.InnerException.Source}{Environment.NewLine}");
                str.Append($"[异常类型]:{ex.InnerException.GetType().Name}{Environment.NewLine}");
                str.Append($"[详细信息]:{ex.InnerException.Message}{Environment.NewLine}");
                str.Append($"[堆栈调用]:{ex.InnerException.StackTrace}");
            }
            return str.ToString();
        }
    }
}