我正在寻找一种方法来在手动关闭控制台应用程序时触发一段代码(用户关闭窗口).一直在尝试:
AppDomain.CurrentDomain.ProcessExit +=
new EventHandler(CurrentDomain_ProcessExit);
Run Code Online (Sandbox Code Playgroud)
但如果手动关闭,上述操作无效.
有没有办法使用.Net调用或我是否需要导入内核DLL并以这种方式执行?
Han*_*ant 106
此代码用于捕获关闭控制台窗口的用户:
using System;
using System.Runtime.InteropServices;
class Program {
static void Main(string[] args) {
handler = new ConsoleEventDelegate(ConsoleEventCallback);
SetConsoleCtrlHandler(handler, true);
Console.ReadLine();
}
static bool ConsoleEventCallback(int eventType) {
if (eventType == 2) {
Console.WriteLine("Console window closing, death imminent");
}
return false;
}
static ConsoleEventDelegate handler; // Keeps it from getting garbage collected
// Pinvoke
private delegate bool ConsoleEventDelegate(int eventType);
[DllImport("kernel32.dll", SetLastError = true)]
private static extern bool SetConsoleCtrlHandler(ConsoleEventDelegate callback, bool add);
}
Run Code Online (Sandbox Code Playgroud)
小心这些限制.您必须快速响应此通知,您有5秒钟完成任务.花费更长时间,Windows会毫不客气地终止你的代码.并且您的方法在工作线程上异步调用,程序的状态完全不可预测,因此可能需要锁定.确保中止不会造成麻烦.例如,将状态保存到文件中时,请确保先保存到临时文件并使用File.Replace().
| 归档时间: |
|
| 查看次数: |
92460 次 |
| 最近记录: |