控制台中禁止使用右上角的关闭按钮,下面是核心代码
1 [DllImport("user32.dll", EntryPoint = "FindWindow")] 2 extern static IntPtr FindWindow(string lpClassName, string lpWindowName); 3 [DllImport("user32.dll", EntryPoint = "GetSystemMenu")] 4 extern static IntPtr GetSystemMenu(IntPtr hWnd, IntPtr bRevert); 5 [DllImport("user32.dll", EntryPoint = "RemoveMenu")] 6 extern static IntPtr RemoveMenu(IntPtr hMenu, uint uPosition, uint uFlags); 7 /// <summary> 8 /// 禁用关闭按钮 9 /// </summary> 10 static void closebtn() 11 { 12 IntPtr windowHandle = FindWindow(null, "test"); 13 IntPtr closeMenu = GetSystemMenu(windowHandle, IntPtr.Zero); 14 uint SC_CLOSE = 0xF060;//系统菜单命令Id 15 RemoveMenu(closeMenu, SC_CLOSE, 0x0); 16 }
控制台主函数入口调用方法
1 protected static void CloseConsole(object sender, ConsoleCancelEventArgs e) 2 { 3 Environment.Exit(0);//提供给操作系统的退出代码。使用 0(零)指示处理已成功完成 4 } 5 static void Main(string[] args) 6 { 7 Console.Title = "test"; 8 closebtn(); 9 Console.CancelKeyPress += new ConsoleCancelEventHandler(CloseConsole); 10 Console.WriteLine("Starting..."); 11 Console.WriteLine("退出请按 Ctrl+C "); 12 Console.Read(); 13 }