C# Console控制命令

时间:2022-10-18 00:09:21

参考博客:C# 控制台程序(命令行程序)设置字体颜色,窗口宽高,光标行数

禁用控制台关闭按钮,参考博客:禁用C#控制台应用程序的关闭按钮

参考博客:c# 控制台程序禁用关闭按钮完美解决

        #region 禁用关闭按钮
        /// <summary>
        /// 禁用关闭按钮
        /// </summary>
        private static void InitDisableClose()
        {
            //与控制台标题名一样的路径
            //string fullPath = System.Environment.CurrentDirectory + "\\" + Process.GetCurrentProcess().ProcessName;
            //根据控制台标题找控制台
            int WINDOW_HANDLER = FindWindow(null, title);
            //找关闭按钮
            IntPtr CLOSE_MENU = GetSystemMenu((IntPtr)WINDOW_HANDLER, IntPtr.Zero);
            int SC_CLOSE = 0xF060;
            //关闭按钮禁用
            RemoveMenu(CLOSE_MENU, SC_CLOSE, 0x0);
        }
        #endregion

控制台输入命令,参考博客:C#入门之控制台输入和输出

        #region 读取控制台命令
        /// <summary>
        /// 读取控制台命令
        /// </summary>
        private static void consoleRead()
        {
            while (true)
            {
                string cmd = Console.ReadLine();
                if (cmd.ToLower() == "exit")
                {
                    System.Environment.Exit();
                    break;
                }
                else if (cmd.ToLower() == "restart")
                {
                    Console.WriteLine("restart");
                }
                Thread.Sleep();
            }
        }
        #endregion

控制台重启

        #region 程序重启
        /// <summary>
        /// 程序重启
        /// </summary>
        public static void Restart()
        {
            Thread reThread = new Thread(new ParameterizedThreadStart(Run));
            object app = System.Environment.CurrentDirectory + "\\" + Process.GetCurrentProcess().ProcessName+".exe";
            reThread.Start(app);
            Thread.CurrentThread.Abort();
        }
        /// <summary>
        /// 运行启动程序
        /// </summary>
        /// <param name="app"></param>
        private static void Run(object app)
        {
            Console.WriteLine("The system will restart!");
            Console.WriteLine("Countdown start...");
            ; i < ; i++)
            {
                Thread.Sleep();//暂停1秒钟
                Console.WriteLine( - i);
            }
            Process ps = new Process();
            ps.StartInfo.FileName = app.ToString();
            ps.Start();
            System.Environment.Exit();
        }
        #endregion