using JinYuan.Helper;
using JinYuan.VirtualDataLibrary;
using System;
using System.Configuration;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Threading;
using System.Windows.Forms;
namespace LargeSquareOne
{
internal static class Program
{
#region 调用系统API
[DllImport("User32.dll")]
private static extern bool ShowWindowAsync(IntPtr hWnd, int cmdShow);
[DllImport("User32.dll")]
private static extern bool SetForegroundWindow(IntPtr hWnd);
private const int SW_MAXIMIZE = 3;
#endregion 调用系统API
///
/// 应用程序的主入口点。
///
[STAThread]
static void Main()
{
var stopwatch = Stopwatch.StartNew();
// 添加全局异常处理
Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);
Application.ThreadException += (sender, e) =>
{
Debug.WriteLine($"[UI线程异常] {e.Exception.Message}");
Debug.WriteLine($"[堆栈] {e.Exception.StackTrace}");
// 检查是否是Max()异常
if (e.Exception is InvalidOperationException &&
e.Exception.Message.Contains("Sequence contains no elements") &&
e.Exception.StackTrace.Contains("Enumerable.Max"))
{
Debug.WriteLine("[诊断] 找到LINQ Max()空集合异常!");
// 输出调用堆栈中的方法名
var stackTrace = new System.Diagnostics.StackTrace(e.Exception, true);
var frames = stackTrace.GetFrames();
if (frames != null)
{
foreach (var frame in frames.Take(5)) // 前5帧
{
var method = frame.GetMethod();
Debug.WriteLine($"[调用链] {method.DeclaringType?.FullName}.{method.Name}");
}
}
}
};
AppDomain.CurrentDomain.UnhandledException += (sender, e) =>
{
var ex = e.ExceptionObject as Exception;
Debug.WriteLine($"[非UI线程异常] {ex?.Message}");
};
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
string strname = Process.GetCurrentProcess().ProcessName;
int a = Process.GetProcessesByName(Process.GetCurrentProcess().ProcessName).Count();
if (Process.GetProcessesByName(Process.GetCurrentProcess().ProcessName).Count() > 1)
{
MessageBox.Show("软件已经启动,请在后台确认。");
Thread.Sleep(1000);
Environment.Exit(0);
return;
}
Process instance = GetRunningInstance();
if (instance == null)
{
AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
ClearMemoryHelper.ClearMemory();
ReadConfig();
try
{
{
FrmLogin frm = new FrmLogin();
if (frm.ShowDialog() == DialogResult.OK)
{
Debug.WriteLine($"[启动] 开始加载主窗体: {stopwatch.ElapsedMilliseconds}ms");
var mainForm = new FrmMain();
Debug.WriteLine($"[启动] 主窗体创建完成: {stopwatch.ElapsedMilliseconds}ms");
Application.Run(mainForm);
Debug.WriteLine($"[启动] 应用程序运行: {stopwatch.ElapsedMilliseconds}ms");
}
}
}
catch (Exception ex)
{
MessageBox.Show($"退出异常:{ex.Message}\n{ex.StackTrace}", "退出告警");
}
}
else
{
// 激活以前的实例
HandleRunningInstance(instance);
}
}
///
/// 配置,数据库初始化
///
public static void ReadConfig()
{
//LogHelper.Instance.InitLog(Application.StartupPath + "\\Logs\\");
LogHelper.Instance.InitLog("D:\\APILog\\Logs\\");
// 读取 XML 文件
CommonMethods.Configxml = CommonMethods.ReadXmlConfig(CommonMethods.xmlFilePath);
string MySlqconnString1 = ConfigurationManager.ConnectionStrings["mysql"].ToString();//本地
string MySlqconnString2 = ConfigurationManager.ConnectionStrings["mysql2"].ToString();//远端
string strDBType = ConfigurationManager.AppSettings["DefaultDb"].ToString();
var connDbType = (SqlSugar.DbType)Enum.Parse(typeof(SqlSugar.DbType), strDBType);
CommonMethods.db.SetConnectionStr(MySlqconnString1, SqlSugar.DbType.MySql);
CommonMethods.dbServer.SetConnectionStr(MySlqconnString2, SqlSugar.DbType.MySql);
CommonMethods.sysConfig.SwipeCardMode = Convert.ToBoolean(CommonMethods.GetConfigValue(CommonMethods.Configxml, "CONFIG_INFO", "EnableCardMode", "false"));//开启刷卡模式?
}
///
/// 当某个异常未被捕获时出现,回调方法
///
///
///
private static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
{
try
{
Exception ex = e.ExceptionObject as Exception;
if (ex != null)
{
LogHelper.Instance.WriteEX(ex);
if (ex.StackTrace.Contains("Finalize"))
{
LogHelper.Instance.WriteEX($"资源释放异常(Finalizer)", ex);
MessageBox.Show($"资源释放失败:{ex.Message}\n这是退出告警的核心原因!", "关键错误");
}
else
{
LogHelper.Instance.WriteEX($"全局未处理异常 ", ex);
}
}
MessageBox.Show($"程序出现大异常,请联系 【金源自动化软件设计部】。\r\n异常信息: {ex.Message}\r\n异常堆栈:{ex.StackTrace}",
"致命错误", MessageBoxButtons.OK, MessageBoxIcon.Stop);
}
finally
{
Application.Exit();
}
}
///
/// 返回正在运行的程序进程
///
///
public static Process GetRunningInstance()
{
Process current = Process.GetCurrentProcess();
Process[] processes = Process.GetProcessesByName(current.ProcessName);
foreach (Process process in processes)
{
if (process.Id != current.Id)
if (Assembly.GetExecutingAssembly().Location.Replace("/", "\\") == current.MainModule.FileName)
return process;
}
return null;
}
///
/// 已经有了就把它激活,并将其窗口放置最前端
///
///
public static void HandleRunningInstance(Process instance)
{
ShowWindowAsync(instance.MainWindowHandle, SW_MAXIMIZE);
SetForegroundWindow(instance.MainWindowHandle);
}
}
}