using GCAS.Code;
using Microsoft.Win32;
using System;
using System.Configuration;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Windows.Forms;
namespace GCAS
{
internal static class Program
{
///
/// 应用程序的主入口点。
///
[STAThread]
private static void Main()
{ //HSL 授权
if (!HslCommunication.Authorization.SetAuthorizationCode("f562cc4c-4772-4b32-bdcd-f3e122c534e3"))
{
LogHelper.WriteError("HSL授权失败");
return;
}
var autoStart = ConfigurationManager.AppSettings["autoStart"];
bool.TryParse(autoStart, out bool isAutoStart);
AutoStart(isAutoStart);
Process instance = RunningInstance();
if (instance == null)
{
try
{
Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);
//处理UI线程异常
Application.ThreadException += new ThreadExceptionEventHandler(Application_ThreadException);
//处理非UI线程异常
AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
var language = ConfigurationManager.AppSettings["language"];
if (string.IsNullOrEmpty(language))
{
config.AppSettings.Settings.Add(new KeyValueConfigurationElement("language", "zh-Hans"));//增加
}
else
{
Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo(language);
}
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new LoginForm());
}
catch (Exception ex)
{
GetExceptionMsg(ex, string.Empty);
//XtraMessageBox.Show(str, "系统错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
else
{
HandleRunningInstance(instance);
}
}
private static void Application_ThreadException(object sender, ThreadExceptionEventArgs e)
{
string str = GetExceptionMsg(e.Exception, e.ToString());
//XtraMessageBox.Show(str, "系统错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
LogHelper.WriteError(str);
}
private static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
{
string str = GetExceptionMsg(e.ExceptionObject as Exception, e.ToString());
//XtraMessageBox.Show(str, "系统错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
LogHelper.WriteError(str);
}
///
/// 生成自定义异常消息
///
/// 异常对象
/// 备用异常消息:当ex为null时有效
/// 异常字符串文本
private static string GetExceptionMsg(Exception ex, string backStr)
{
StringBuilder sb = new StringBuilder();
sb.AppendLine("****************************异常文本****************************");
sb.AppendLine("【出现时间】:" + DateTime.Now.ToString());
if (ex != null)
{
sb.AppendLine("【异常类型】:" + ex.GetType().Name);
sb.AppendLine("【异常信息】:" + ex.Message);
sb.AppendLine("【堆栈调用】:" + ex.StackTrace);
}
else
{
sb.AppendLine("【未处理异常】:" + backStr);
}
sb.AppendLine("***************************************************************");
return sb.ToString();
}
[DllImport("User32.dll", EntryPoint = "FindWindow")]
private static extern IntPtr FindWindow(string lpClassName, string lpWindowName);
///
/// 该函数设置由不同线程产生的窗口的显示状态。
///
/// 窗口句柄
/// 指定窗口如何显示。查看允许值列表,请查阅ShowWlndow函数的说明部分。
/// 如果函数原来可见,返回值为非零;如果函数原来被隐藏,返回值为零。
[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 WS_SHOWNORMAL = 1;
///
/// 获取正在运行的实例,没有运行的实例返回null;
///
public 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;
}
///
/// 显示已运行的程序。
///
public static void HandleRunningInstance(Process instance)
{
var mainHandle = instance.MainWindowHandle;
if (mainHandle == IntPtr.Zero)
{
mainHandle = FindWindow(null, "电子秤称重管理系统-灰渣吊");
}
ShowWindowAsync(instance.MainWindowHandle, WS_SHOWNORMAL); //显示,可以注释掉
SetForegroundWindow(instance.MainWindowHandle); //放到前端
}
///
/// 修改程序在注册表中的键值
///
/// true:开机启动,false:不开机自启
private static void AutoStart(bool isAuto = true, bool showinfo = true)
{
try
{
if (isAuto == true)
{
RegistryKey R_local = Registry.CurrentUser;
RegistryKey R_run = R_local.CreateSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Run");
R_run.SetValue("电子秤称重管理系统-垃圾吊", Application.ExecutablePath);
R_run.Close();
R_local.Close();
}
else
{
RegistryKey R_local = Registry.CurrentUser;
RegistryKey R_run = R_local.CreateSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Run");
R_run.DeleteValue("电子秤称重管理系统-垃圾吊", false);
R_run.Close();
R_local.Close();
}
}
catch (Exception)
{
if (showinfo)
MessageBox.Show("您需要管理员权限修改", "提示");
}
}
}
}