AIMS/AIMS/Program.cs
2023-08-16 21:32:51 +08:00

239 lines
9.0 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
using System.Threading;
using HelperDB;
using System.Threading.Tasks;
using AIMSExtension;
using System.Runtime.InteropServices;
using System.Diagnostics;
using System.Reflection;
using System.IO;
using System.Xml.Linq;
using CCIS.Shared;
using Serilog;
using Serilog.Core;
namespace AIMS
{
static class Program
{
static Program()
{
}
/// <summary>
/// 应用程序的主入口点。
/// </summary>
[STAThread]
static void Main(string[] args)
{
try
{
Log.Logger = CreateBootstrapLogger();
Log.Information("Hello, {Name}!", Environment.UserName);
SharedContext.CreateDefault(args);
Log.Information("Initialising.");
MainStart(args);
Log.Information("Finsh.");
}
catch (Exception e)
{
Log.Error(e, "Application terminated unexpectedly.");
}
finally
{
// Important to call at exit so that batched events are flushed.
Log.CloseAndFlush();
}
}
static void MainStart(string[] args)
{
/**
* 当前用户是管理员的时候,直接启动应用程序
* 如果不是管理员,则使用启动对象启动程序,以确保使用管理员身份运行
*/
//获得当前登录的Windows用户标示
System.Security.Principal.WindowsIdentity identity = System.Security.Principal.WindowsIdentity.GetCurrent();
//创建Windows用户主题
Application.EnableVisualStyles();
System.Security.Principal.WindowsPrincipal principal = new System.Security.Principal.WindowsPrincipal(identity);
//判断当前登录用户是否为管理员
if (principal.IsInRole(System.Security.Principal.WindowsBuiltInRole.Administrator))
{
//如果是管理员,则直接运行
if (PublicMethod.FindProcess("AIMSAutoUpdate"))
{
return;
}
BindExceptionHandler();
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
//Process instance = RunningInstance();
//if (instance == null)
//{
UpdateProgram(args);
Application.Run(new FormLogin());
//}
//else
//{
// /*1.2 已经有一个实例在运行*/
// HandleRunningInstance(instance);
//}
}
else
{
//创建启动对象
System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();
//设置运行文件
startInfo.FileName = System.Windows.Forms.Application.ExecutablePath;
//设置启动参数
startInfo.Arguments = String.Join(" ", args);
//设置启动动作,确保以管理员身份运行
startInfo.Verb = "runas";
//如果不是管理员则启动UAC
System.Diagnostics.Process.Start(startInfo);
//退出
System.Windows.Forms.Application.Exit();
}
}
static void UpdateProgram(string[] args)
{
try
{
//服务器版本号
PublicMethod.NowVersion = PublicMethod.GetVersion();
string localXmlFile = Application.StartupPath + "\\UpdateList.xml";
if (!File.Exists(localXmlFile)) return;
//读xml版本号
XElement xe = XElement.Load(localXmlFile);
string FtpAddress = xe.Element("FtpAddress").Value;
string User = xe.Element("User").Value;
string PassWord = xe.Element("PassWord").Value;
string SysName = xe.Element("SysName").Value;
string serverXmlFile = string.Empty;
Version nowvs = new Version(xe.Element("Version").Value);
Version vs = new Version(PublicMethod.NowVersion);
if (nowvs.CompareTo(vs) == 0) return;
try
{
//获取服务器地址
string UpdaterUrl = FtpAddress + "//" + "UpdateList.xml";
//与服务器连接,下载更新配置文件
FTPTransmission.download(localXmlFile, UpdaterUrl, User, PassWord);
Process sprs = new Process();
sprs.StartInfo.FileName = Application.StartupPath + "\\AIMSAutoUpdate.exe";
sprs.StartInfo.Arguments = SysName;
sprs.Start();
}
catch (Exception)
{
return;
}
}
catch
{
//MessageBox.Show("与服务器连接失败,操作超时!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
return;
}
}
/// 绑定程序中的异常处理
/// </summary>
static void BindExceptionHandler()
{
//设置应用程序处理异常方式ThreadException处理
Application.ThreadException += new System.Threading.ThreadExceptionEventHandler(Application_ThreadException);
//处理UI线程异常
//Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);
//处理未捕获的异常
AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
}
static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
{
try
{
MessageBox.Show(((Exception)e.ExceptionObject).Message + "\r\n" + ((Exception)e.ExceptionObject).StackTrace, "系统信息");
AIMSExtension.PublicMethod.WriteLog((Exception)e.ExceptionObject);
}
catch
{
Application.Exit();
}
}
static void Application_ThreadException(object sender, System.Threading.ThreadExceptionEventArgs e)
{
try
{
if (e.Exception.Message.Contains("error: 40"))
{
MessageBox.Show("当前网络异常 请检查网络!!!", "系统信息");
AIMSExtension.PublicMethod.WriteLog(e.Exception);
}
else
{
MessageBox.Show(e.Exception.Message + "\r\n" + e.Exception.StackTrace, "系统信息");
AIMSExtension.PublicMethod.WriteLog(e.Exception);
}
}
catch
{
Application.Exit();
}
}
/// <summary>
/// Creates a logger used during application initialisation.
/// <see href="https://nblumhardt.com/2020/10/bootstrap-logger/"/>.
/// </summary>
/// <returns>A logger that can load a new configuration.</returns>
private static Logger CreateBootstrapLogger() =>
new LoggerConfiguration()
//.WriteTo.Console()
.WriteTo.File("logs\\bootstrap.log", rollingInterval: RollingInterval.Day)
.CreateLogger();
#region
private static Process RunningInstance()
{
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;
}
private static void HandleRunningInstance(Process instance)
{
ShowWindowAsync(instance.MainWindowHandle, 4); //调用api函数正常显示窗口
SetForegroundWindow(instance.MainWindowHandle); //将窗口放置最前端
}
[DllImport("User32.dll")]
private static extern bool ShowWindowAsync(System.IntPtr hWnd, int cmdShow);
[DllImport("User32.dll")]
private static extern bool SetForegroundWindow(System.IntPtr hWnd);
#endregion
}
}