SetConsoleCtrlHandler
有時(shí)候運(yùn)行在服務(wù)器上的控制臺(tái)程序,需要記錄詳細(xì)的運(yùn)行日志,這就需要對(duì)程序關(guān)閉進(jìn)行日志記錄,以便能根據(jù)日志了解程序的運(yùn)行狀況。比如正在運(yùn)行的程序被 人不小心關(guān)閉了,導(dǎo)致最終任務(wù)沒有運(yùn)行成功,這時(shí)日志也沒有錯(cuò)誤記錄,對(duì)分析原因造成不便,記錄了關(guān)閉事件日志后就能了解到這種情況是程序被終止了。這樣 注意通過消息鉤子來(lái)實(shí)現(xiàn),通過調(diào)用WIN32 API SetConsoleCtrlHandler方法來(lái)實(shí)現(xiàn),具體代碼如下:
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);
//當(dāng)用戶關(guān)閉Console時(shí),系統(tǒng)會(huì)發(fā)送次消息
private const int CTRL_CLOSE_EVENT = 2;
//Ctrl+C,系統(tǒng)會(huì)發(fā)送次消息
private const int CTRL_C_EVENT = 0;
//Ctrl+break,系統(tǒng)會(huì)發(fā)送次消息
private const int CTRL_BREAK_EVENT = 1;
//用戶退出(注銷),系統(tǒng)會(huì)發(fā)送次消息
private const int CTRL_LOGOFF_EVENT = 5;
//系統(tǒng)關(guān)閉,系統(tǒng)會(huì)發(fā)送次消息
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;//表示阻止響應(yīng)系統(tǒng)對(duì)該程序的操作
return false;//忽略處理,讓系統(tǒng)進(jìn)行默認(rèn)操作
}
}
}
CTRL_CLOSE_EVENT 這些都是在C:\Program Files\Microsoft Visual Studio 8\VC\PlatformSDK\Include\WinCon.h中定義的,c或者c++調(diào)用包含這個(gè)頭文件就可以。
return true的時(shí)候關(guān)閉的時(shí)候會(huì)產(chǎn)生應(yīng)用程序無(wú)法關(guān)閉的錯(cuò)誤,不知道什么原因。return false則不會(huì)。根據(jù)msdn上的方法說(shuō)明 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. 按照這個(gè)解釋,返回true也不應(yīng)該出現(xiàn)應(yīng)用程序無(wú)法關(guān)閉的錯(cuò)誤,不知道是什么原因。
posted on 2012-04-24 22:44 多彩人生 閱讀(1219) 評(píng)論(0) 編輯 收藏 引用