111,119
社区成员
发帖
与我相关
我的任务
分享using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Net;
namespace ConsoleColsed
{
public delegate bool ConsoleCtrlDelegate(int dwCtrlType);
public class ClsMain
{
[DllImport("kernel32.dll")]
private static extern bool SetConsoleCtrlHandler(ConsoleCtrlDelegate HandlerRoutine, bool Add);
[STAThread]
static void Main()
{
ConsoleCtrlDelegate newDelegate = new ConsoleCtrlDelegate(HandlerRoutine);
bool bRet = SetConsoleCtrlHandler(newDelegate, true);
string server = Dns.GetHostName();//问题出在这一行,在控制台按Ctrl+C会蹦异常,注释掉这一行就没有问题
Console.Read();
}
private static bool HandlerRoutine(int CtrlType)
{
const int CTRL_CLOSE_EVENT = 2;
const int CTRL_C_EVENT = 0;
switch (CtrlType)
{
case CTRL_CLOSE_EVENT:
Console.WriteLine("Close");
break;
case CTRL_C_EVENT:
Console.WriteLine("Ctrl+C");
break;
}
return false;
}
}
}