类型:转载 责任编辑:asp.net 日期:2007/05/23
热门软件下载:
在窗体中,我能捕捉窗体的关闭信息,可以根据事件驱动捕捉。
请问console程序的关闭事件是否也能捕捉到呢?
或者说console程序关闭(就是那个小X的按钮)是什么样的机制呢?
网友回答:
能做到,只能用API来实现,不过麻烦点而已:
下面代码刚刚做的,测试通过:
======================================================
using System;
using System.Windows.Forms;
using System.Diagnostics;
using System.Runtime.InteropServices;
namespace WindowsApplication2
{
public delegate bool ConsoleCtrlDelegate(int dwCtrlType);
public class ClsMain
{
//The SetConsoleCtrlHandler function adds or removes an application-defined HandlerRoutine function
//from the list of handler functions for the calling process.
[DllImport("kernel32.dll")]
private static extern bool SetConsoleCtrlHandler(ConsoleCtrlDelegate HandlerRoutine,bool Add);
//一個Ctrl + C的信號被接收,該信號或來自鍵盤,或來自GenerateConsoleCtrlEvent 函數
private const int CTRL_C_EVENT = 0;
//一個 Ctrl + Break 信號被接收,該信號或來自鍵盤,或來自GenerateConsoleCtrlEvent 函數
private const int CTRL_BREAK_EVENT = 1;
//當用戶系統關閉Console時,系統會發送此信號到此
private const int CTRL_CLOSE_EVENT = 2;
//當用戶退出系統時系統會發送這個信號給所有的Console程序。該信號不能顯示是哪個用戶退出。
private const int CTRL_LOGOFF_EVENT = 5;
//當系統將要關閉時會發送此信號到所有Console程序
private const int CTRL_SHUTDOWN_EVENT = 6;
[STAThread]
static void Main()
{
ClsMain cls=new ClsMain();
}
public ClsMain()
{
// 用API安装事件处理
ConsoleCtrlDelegate newDelegate=new ConsoleCtrlDelegate(HandlerRoutine);
bool bRet=SetConsoleCtrlHandler(newDelegate,true);
if(bRet==false) //安装事件处理失败
{
Debug.WriteLine("失败");
}
else
{
Console.WriteLine("ok");
Console.Read();
}
}
/// <summary>
/// 处理消息的事件
/// </summary>
private static bool HandlerRoutine(int CtrlType)
{
switch(CtrlType)
{
case CTRL_CLOSE_EVENT: //用户要关闭Console了
Debug.WriteLine("Close");
break;
}
return false;
}
}
}