Program.cs 5.9 KB
using ConfigHelper;
using log4net.Config;
using Microsoft.Win32.TaskScheduler;
using OnlineStore.Common;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Linq;
using System.Runtime.InteropServices;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace TheMachine
{
    static class Program
    {
        /// <summary>
        /// 应用程序的主入口点。
        /// </summary>
        [STAThread]
        static void Main()
        {

            _ = new Mutex(true, Application.ProductName, out bool ret);
            if (!ret)
            {
                IntPtr formhwnd = FindWindow(null, Setting_Init.App_Title+" "+ Setting_Init.Device_CID);
                ShowWindow(formhwnd, SW_RESTORE);
                SwitchToThisWindow(formhwnd, true);
                //MessageBox.Show("该程序已经启动", "提示信息", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            var currnetdrive = System.IO.Path.GetPathRoot(Application.StartupPath);
            var drives = System.IO.DriveInfo.GetDrives();
            foreach (var drive in drives) {
                if (drive.Name.ToLower() == "c:\\"
                    || drive.Name.ToLower() == currnetdrive.ToLower()
                    ) {

                    var spacegb = drive.AvailableFreeSpace / 1024 / 1024 / 1024;
                    if (spacegb <= 2)
                    {
                        MessageBox.Show(drive.Name+" is not enough disk space, check it please.", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                }
            }
            AddOrUpdateStartupTask();
            Config.LoadMyConfig(new Setting_Init().GetType());
            Application.ThreadException += Application_ThreadException;
            Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);
            AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;

            Environment.CurrentDirectory = Application.StartupPath;
            XmlConfigurator.Configure();

            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new Form1());
        }

        private static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            LogUtil.error(e.ToString());
        }

        private static void Application_ThreadException(object sender, ThreadExceptionEventArgs e)
        {
            LogUtil.error(e.ToString());
        }



        #region Win32函数的声明

        /// <summary>
        /// 找到某个窗口与给出的类别名和窗口名相同窗口 
        /// </summary>
        /// <param name="lpClassName">类别名</param>
        /// <param name="lpWindowName">窗口名</param>
        /// <returns>成功找到返回窗口句柄,否则返回null</returns>
        [DllImport("user32.dll")]
        public static extern IntPtr FindWindow(string lpClassName, string lpWindowName);

        /// <summary>
        /// 切换到窗口并把窗口设入前台,类似 SetForegroundWindow方法的功能
        /// </summary>
        /// <param name="hWnd">窗口句柄</param>
        /// <param name="fAltTab">True代表窗口正在通过Alt/Ctrl +Tab被切换</param>
        [DllImport("user32.dll ", SetLastError = true)]
        static extern void SwitchToThisWindow(IntPtr hWnd, bool fAltTab);

        /// <summary>
        ///  设置窗口的显示状态 
        /// </summary>
        /// <param name="hWnd">窗口句柄</param>
        /// <param name="cmdShow">指示窗口如何被显示</param>
        /// <returns>如果窗体之前是可见,返回值为非零;如果窗体之前被隐藏,返回值为零</returns>
        [DllImport("user32.dll", EntryPoint = "ShowWindow", CharSet = CharSet.Auto)]
        public static extern int ShowWindow(IntPtr hwnd, int nCmdShow);
        public const int SW_RESTORE = 9;

        #endregion
        public static void AddOrUpdateStartupTask()
        {
            // 获取当前程序的路径和名称
            string appPath = Process.GetCurrentProcess().MainModule.FileName;
            string TaskName = "AutoStartup_" + Process.GetCurrentProcess().MainModule.ModuleName;
            // 创建或更新计划任务
            using (TaskService taskService = new TaskService())
            {
                // 获取任务定义,如果不存在则创建新的任务定义
                TaskDefinition taskDefinition;
                if (taskService.GetTask(TaskName) != null)
                {
                    taskDefinition = taskService.GetTask(TaskName).Definition;
                }
                else
                {
                    taskDefinition = taskService.NewTask();
                    taskDefinition.RegistrationInfo.Description = TaskName;

                }
                if (taskDefinition.Triggers.Count == 0 || taskDefinition.Triggers[0].TriggerType != TaskTriggerType.Logon)
                {
                    // 设置触发器为用户登录后启动
                    LogonTrigger logonTrigger = (LogonTrigger)taskDefinition.Triggers.Add(new LogonTrigger());
                    logonTrigger.Delay = TimeSpan.FromSeconds(5);
                }

                // 设置操作为启动应用程序
                taskDefinition.Actions.Clear();
                taskDefinition.Actions.Add(new ExecAction(appPath, null, System.IO.Path.GetDirectoryName(appPath)));

                // 设置任务的运行权限为管理员权限
                taskDefinition.Principal.RunLevel = TaskRunLevel.Highest;

                // 保存任务
                taskService.RootFolder.RegisterTaskDefinition(TaskName, taskDefinition, TaskCreation.CreateOrUpdate, null, null, TaskLogonType.InteractiveToken, null);
            }
        }
    }
}