C# 控制台实现关闭前的操作,并使关闭按钮无法使用 收藏
控制台的按钮真不好控制,最近的一个项目中,要对关闭控制台前对缓存数据进行数据库写入,所以就有了这么一个情境,实现的代码如下:
- namespace ConsoleApplication3
- {
- class Program
- {
- [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 closebtn()
- {
- //IntPtr windowHandle = FindWindow(null, Process.GetCurrentProcess().MainModule.FileName);
- IntPtr windowHandle = FindWindow(null, "sample");
- IntPtr closeMenu = GetSystemMenu(windowHandle, IntPtr.Zero);
- uint SC_CLOSE = 0xF060;
- RemoveMenu(closeMenu, SC_CLOSE, 0x0);
- }
- static void Main(string[] args)
- {
- Console.Title = "sample";
- closebtn();
- Console.CancelKeyPress += new ConsoleCancelEventHandler(CloseConsole);
- Console.WriteLine("Starting...");
- Console.Read();
- }
- #region CloseConsole 关闭时的事件
- /// <summary>
- /// 关闭时的事件
- /// </summary>
- /// <param name="sender">对象</param>
- /// <param name="e">参数</param>
- protected static void CloseConsole(object sender, ConsoleCancelEventArgs e)
- {
- aDataBaseBll.AcceptEmailChanges();
- aDataBaseBll.AcceptTaoBaoChanges();
- }
- #endregion
- }
- }
特别注意窗口名称的引用!