C# Win32控制台應用程式忽略 Ctrl + C,阻止程式退出,這裡使用到了Windows API SetConsoleCtrlHandler函數
注意:在VS中調試執行時,在處理常式常式中設定斷點,不會中斷;會提示:無可用源,如:
完整範例程式碼:
using System;using System.Collections.Generic;using System.Text;using System.Diagnostics;using System.Runtime.InteropServices;using System.Threading;/************************************************************************//* CSharp_Win32控制台應用程式忽略 Ctrl + C * Powered by:testcs_dn * Blog:http://www.php.cn/ *//************************************************************************/namespace CSharp_Win32控制台應用程式忽略CtrlC{ //定義處理常式委託 public delegate bool ConsoleCtrlDelegate(int ctrlType); class Program { //匯入SetCtrlHandlerHandler API [DllImport("kernel32.dll")] private static extern bool SetConsoleCtrlHandler(ConsoleCtrlDelegate HandlerRoutine, bool Add); //當使用者關閉Console時,系統會發送次訊息 private const int CTRL_CLOSE_EVENT = 2; //Ctrl+C,系統會發送次訊息 private const int CTRL_C_EVENT = 0; //Ctrl+break,系統會發送次訊息 private const int CTRL_BREAK_EVENT = 1; //使用者退出(登出),系統會發送次訊息 private const int CTRL_LOGOFF_EVENT = 5; //系統關閉,系統會發送次訊息 private const int CTRL_SHUTDOWN_EVENT = 6; static void Main(string[] args) { Program cls = new Program(); //Console.ReadKey(); } public Program() { ConsoleCtrlDelegate consoleDelegete = new ConsoleCtrlDelegate(HandlerRoutine); bool bRet = SetConsoleCtrlHandler(consoleDelegete, true); if (bRet == false) //安裝事件處理失敗 { Console.WriteLine("error"); while (true) { Console.WriteLine("..."); Thread.Sleep(1000); } } else { Console.WriteLine("ok"); while (true) { Console.WriteLine("..."); Thread.Sleep(1000); } } } /// <summary> /// 處理常式常式,在這裡編寫對指定事件的處理常式代碼 /// 注意:在VS中調試執行時,在這裡設定斷點,但不會中斷;會提示:無可用源; /// </summary> /// <param name="CtrlType"></param> /// <returns></returns> private static bool HandlerRoutine(int ctrlType) { switch(ctrlType) { case CTRL_C_EVENT: Console.WriteLine("C"); return true; //這裡返回true,表示阻止響應系統對該程式的操作 //break; case CTRL_BREAK_EVENT: Console.WriteLine("BREAK"); break; case CTRL_CLOSE_EVENT: Console.WriteLine("CLOSE"); break; case CTRL_LOGOFF_EVENT: Console.WriteLine("LOGOFF"); break; case CTRL_SHUTDOWN_EVENT: Console.WriteLine("SHUTDOWN"); break; } //return true;//表示阻止響應系統對該程式的操作 return false;//忽略處理,讓系統進行預設操作 } }}