C# 控制台实现关闭前的操作,并使关闭按钮无法使用

来源:互联网 发布:做详情页的软件 编辑:程序博客网 时间:2024/06/03 22:08

C# 控制台实现关闭前的操作,并使关闭按钮无法使用 收藏

  控制台的按钮真不好控制,最近的一个项目中,要对关闭控制台前对缓存数据进行数据库写入,所以就有了这么一个情境,实现的代码如下:

 

view plaincopy to clipboardprint?
·········10········20········30········40········50········60········70········80········90········100·······110·······120·······130·······140·······150
  1. namespace ConsoleApplication3   
  2. {   
  3.     class Program   
  4.     {   
  5.         [DllImport("user32.dll", EntryPoint = "FindWindow")]   
  6.         extern static IntPtr FindWindow(string lpClassName, string lpWindowName);   
  7.         [DllImport("user32.dll", EntryPoint = "GetSystemMenu")]   
  8.         extern static IntPtr GetSystemMenu(IntPtr hWnd, IntPtr bRevert);   
  9.         [DllImport("user32.dll", EntryPoint = "RemoveMenu")]   
  10.         extern static IntPtr RemoveMenu(IntPtr hMenu, uint uPosition, uint uFlags);   
  11.         static void closebtn()   
  12.         {   
  13.             //IntPtr windowHandle = FindWindow(null, Process.GetCurrentProcess().MainModule.FileName);   
  14.             IntPtr windowHandle = FindWindow(null"sample");   
  15.             IntPtr closeMenu = GetSystemMenu(windowHandle, IntPtr.Zero);   
  16.             uint SC_CLOSE = 0xF060;   
  17.             RemoveMenu(closeMenu, SC_CLOSE, 0x0);   
  18.         }   
  19.         static void Main(string[] args)   
  20.         {   
  21.             Console.Title = "sample";   
  22.             closebtn();   
  23.             Console.CancelKeyPress += new ConsoleCancelEventHandler(CloseConsole);    
  24.             Console.WriteLine("Starting...");   
  25.             Console.Read();   
  26.         }  
  27.         #region CloseConsole 关闭时的事件   
  28.         /// <summary>   
  29.         /// 关闭时的事件   
  30.         /// </summary>   
  31.         /// <param name="sender">对象</param>   
  32.         /// <param name="e">参数</param>   
  33.         protected static void CloseConsole(object sender, ConsoleCancelEventArgs e)   
  34.         {   
  35.             aDataBaseBll.AcceptEmailChanges();   
  36.             aDataBaseBll.AcceptTaoBaoChanges();   
  37.         }  
  38.         #endregion   
  39.     }   
  40. }  

 

特别注意窗口名称的引用!

原创粉丝点击