.NET控制台程序监听程序退出

There are mainly 2 types of Win32 applications, console application and window application. They have different way in handling application exit. To force Window application to exit, you need to send out WM_CLOSE message to the main window handle. That's pretty simple to handle. You can hook up to Application.ApplicationExit or Form.Close at the form level. However, in a console application, it is a little bit different. Console applications are somehow modeled after DOS console application where usually an application exits when stdin is dead or Ctrl+C is pressed. To handle this properly in C#, you can set a delegate to SetConsoleCtrlHandler.You will have an opportunity to clean up resource or finish your work before the application actually exits. 

// Declare the SetConsoleCtrlHandler function
// as external and receiving a delegate.

[DllImport("Kernel32")]
public static extern bool SetConsoleCtrlHandler(HandlerRoutine Handler, bool Add);

// A delegate type to be used as the handler routine
// for SetConsoleCtrlHandler.
public delegate bool HandlerRoutine(CtrlTypes CtrlType);

// An enumerated type for the control messages
// sent to the handler routine.
public enum CtrlTypes
{
    CTRL_C_EVENT = 0,
    CTRL_BREAK_EVENT,
    CTRL_CLOSE_EVENT,
    CTRL_LOGOFF_EVENT = 5,
    CTRL_SHUTDOWN_EVENT
}

private static bool ConsoleCtrlCheck(CtrlTypes ctrlType)
{
    // Put your own handler here
    return true;
}

...

SetConsoleCtrlHandler(new HandlerRoutine(ConsoleCtrlCheck), true);

转自Geekswithblogs.

转载于:https://www.cnblogs.com/allanli/p/3288987.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
SetCooperativeLevel是DirectInput API中的一个方法,用于设置输入设备与应用程序的协作级别。在.NET控制台应用程序中,可以通过以下步骤使用该方法: 1. 引入DirectInput命名空间:using Microsoft.DirectX.DirectInput; 2. 创建DirectInput对象:DirectInput dinput = new DirectInput(); 3. 获取输入设备:Device device = new Device(dinput, deviceGuid); 其中deviceGuid是输入设备的GUID,可以通过DirectInput.GetDevices方法获取。 4. 设置协作级别:device.SetCooperativeLevel(windowHandle, CooperativeLevel); 其中windowHandle是应用程序窗口句柄,可以通过Process.GetCurrentProcess().MainWindowHandle获取;CooperativeLevel是协作级别,可以是以下值之一: - Exclusive:独占模式,应用程序对输入设备的控制权最高,其他应用程序无法访问输入设备。 - NonExclusive:非独占模式,应用程序与其他应用程序共享输入设备,但应用程序优先级最高。 - Foreground:前台模式,应用程序与其他前台应用程序共享输入设备,但后台应用程序无法访问输入设备。 - Background:后台模式,应用程序与其他后台应用程序共享输入设备,但前台应用程序优先级最高。 5. 设置数据格式:device.SetDataFormat(DeviceDataFormat.Keyboard); 其中DeviceDataFormat.Keyboard表示输入设备为键盘。 6. 开始接收输入数据:device.Acquire(); 以上就是在.NET控制台应用程序中使用SetCooperativeLevel方法的基本步骤。需要注意的是,该方法只对DirectInput输入设备有效,对于其他类型的输入设备,应该使用相应的API进行控制。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值