SetConsoleCtrlHandler
有時候運行在服務器上的控制臺程序,需要記錄詳細的運行日志,這就需要對程序關閉進行日志記錄,以便能根據日志了解程序的運行狀況。比如正在運行的程序被 人不小心關閉了,導致最終任務沒有運行成功,這時日志也沒有錯誤記錄,對分析原因造成不便,記錄了關閉事件日志后就能了解到這種情況是程序被終止了。這樣 注意通過消息鉤子來實現,通過調用WIN32 API SetConsoleCtrlHandler方法來實現,具體代碼如下:
using System;
using System.Windows.Forms;
using System.Diagnostics;
using System.Runtime.InteropServices;
namespace ConsoleColsed
{
public delegate bool ConsoleCtrlDelegate(int ctrlType);
class Program
{
[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) //安裝事件處理失敗
{
Debug.WriteLine("error");
}
else
{
Console.WriteLine("ok");
Console.Read();
}
}
private static bool HandlerRoutine(int ctrlType)
{
switch(ctrlType)
{
case CTRL_C_EVENT:
MessageBox.Show("C");
break;
case CTRL_BREAK_EVENT:
MessageBox.Show("BREAK");
break;
case CTRL_CLOSE_EVENT:
MessageBox.Show("CLOSE");
break;
case CTRL_LOGOFF_EVENT:
break;
case CTRL_SHUTDOWN_EVENT:
break;
}
//return true;//表示阻止響應系統對該程序的操作
return false;//忽略處理,讓系統進行默認操作
}
}
}
CTRL_CLOSE_EVENT 這些都是在C:\Program Files\Microsoft Visual Studio 8\VC\PlatformSDK\Include\WinCon.h中定義的,c或者c++調用包含這個頭文件就可以。
return true的時候關閉的時候會產生應用程序無法關閉的錯誤,不知道什么原因。return false則不會。根據msdn上的方法說明 If the function handles the control signal, it should return TRUE. If it returns FALSE, the next handler function in the list of handlers for this process is used. 按照這個解釋,返回true也不應該出現應用程序無法關閉的錯誤,不知道是什么原因。