Skip to content

Commit 0624177

Browse files
committed
Update Program.cs
1 parent 1dec4df commit 0624177

File tree

1 file changed

+22
-1
lines changed

1 file changed

+22
-1
lines changed

src/DiffEngineWord/Program.cs

Lines changed: 22 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
static partial class Program
44
{
55
static dynamic? _word;
6+
static readonly ConsoleCtrlDelegate _consoleCtrlHandler = ConsoleCtrlHandler;
67

78
static int Main(string[] args)
89
{
@@ -35,6 +36,8 @@ static int Main(string[] args)
3536
}
3637

3738
Console.CancelKeyPress += OnCancelKeyPress;
39+
AppDomain.CurrentDomain.ProcessExit += OnProcessExit;
40+
SetConsoleCtrlHandler(_consoleCtrlHandler, true);
3841

3942
_word = Activator.CreateInstance(wordType)!;
4043
dynamic word = _word;
@@ -90,7 +93,19 @@ static int Main(string[] args)
9093
return 0;
9194
}
9295

93-
static void OnCancelKeyPress(object? sender, ConsoleCancelEventArgs e)
96+
static void OnCancelKeyPress(object? sender, ConsoleCancelEventArgs e) =>
97+
CloseWord();
98+
99+
static void OnProcessExit(object? sender, EventArgs e) =>
100+
CloseWord();
101+
102+
static bool ConsoleCtrlHandler(int ctrlType)
103+
{
104+
CloseWord();
105+
return false;
106+
}
107+
108+
static void CloseWord()
94109
{
95110
if (_word == null)
96111
{
@@ -112,4 +127,10 @@ static void OnCancelKeyPress(object? sender, ConsoleCancelEventArgs e)
112127

113128
[LibraryImport("user32.dll")]
114129
internal static partial uint GetWindowThreadProcessId(IntPtr hWnd, out int processId);
130+
131+
[LibraryImport("kernel32.dll")]
132+
[return: MarshalAs(UnmanagedType.Bool)]
133+
private static partial bool SetConsoleCtrlHandler(ConsoleCtrlDelegate handler, [MarshalAs(UnmanagedType.Bool)] bool add);
134+
135+
delegate bool ConsoleCtrlDelegate(int ctrlType);
115136
}

0 commit comments

Comments
 (0)