隐藏

C#控制台程序关闭快速编辑

发布:2023/3/26 0:34:47作者:管理员 来源:本站 浏览次数:325

之前接的一个项目,客户端反馈服务连接不上,一番排查发现客户启动控制台服务后会点击一下窗口,说是确保进程运行,但是windows的控制台窗口在启用快速编辑模式的情况下点击窗口会进入到Console.Write流程,导致逻辑流程处于等待状态。因为项目有些时间了,让客户手动修改了禁用快速编辑模式解决问题,这里记录一下后续有类似项目,直接在程序内禁用快速编辑,防止类似问题。


   #region 关闭控制台 快速编辑模式、插入模式

           const int STD_INPUT_HANDLE = -10;

           const uint ENABLE_QUICK_EDIT_MODE = 0x0040;

           const uint ENABLE_INSERT_MODE = 0x0020;

           [DllImport("kernel32.dll", SetLastError = true)]

           internal static extern IntPtr GetStdHandle(int hConsoleHandle);

           [DllImport("kernel32.dll", SetLastError = true)]

           internal static extern bool GetConsoleMode(IntPtr hConsoleHandle, out uint mode);

           [DllImport("kernel32.dll", SetLastError = true)]

           internal static extern bool SetConsoleMode(IntPtr hConsoleHandle, uint mode);

   

           public static void DisbleQuickEditMode()

           {

               IntPtr hStdin = GetStdHandle(STD_INPUT_HANDLE);

               uint mode;

               GetConsoleMode(hStdin, out mode);

               mode &= ~ENABLE_QUICK_EDIT_MODE;//移除快速编辑模式

               mode &= ~ENABLE_INSERT_MODE;      //移除插入模式

               SetConsoleMode(hStdin, mode);

           }

           #endregion


   #region 设置控制台标题 禁用关闭按钮

   

           [DllImport("user32.dll", EntryPoint = "FindWindow")]

           extern static IntPtr FindWindow(string lpClassName, string lpWindowName);

           [DllImport("user32.dll", EntryPoint = "GetSystemMenu")]

           extern static IntPtr GetSystemMenu(IntPtr hWnd, IntPtr bRevert);

           [DllImport("user32.dll", EntryPoint = "RemoveMenu")]

           extern static IntPtr RemoveMenu(IntPtr hMenu, uint uPosition, uint uFlags);

   

           static void DisbleClosebtn()

           {

               IntPtr windowHandle = FindWindow(null, "控制台标题");

               IntPtr closeMenu = GetSystemMenu(windowHandle, IntPtr.Zero);

               uint SC_CLOSE = 0xF060;

               RemoveMenu(closeMenu, SC_CLOSE, 0x0);

           }

           protected static void CloseConsole(object sender, ConsoleCancelEventArgs e)

           {

               Environment.Exit(0);

           }

           #endregion