Skip to content

Commit 1dec4df

Browse files
committed
Update Program.cs
1 parent 4b33a48 commit 1dec4df

File tree

1 file changed

+27
-1
lines changed

1 file changed

+27
-1
lines changed

src/DiffEngineWord/Program.cs

Lines changed: 27 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,8 @@
22

33
static partial class Program
44
{
5+
static dynamic? _word;
6+
57
static int Main(string[] args)
68
{
79
if (args.Length != 2)
@@ -32,7 +34,10 @@ static int Main(string[] args)
3234
return 1;
3335
}
3436

35-
dynamic word = Activator.CreateInstance(wordType)!;
37+
Console.CancelKeyPress += OnCancelKeyPress;
38+
39+
_word = Activator.CreateInstance(wordType)!;
40+
dynamic word = _word;
3641

3742
// WdAlertLevel.wdAlertsNone = 0
3843
word.DisplayAlerts = 0;
@@ -80,10 +85,31 @@ static int Main(string[] args)
8085
// Release COM objects
8186
Marshal.ReleaseComObject(comparedDoc);
8287
Marshal.ReleaseComObject(word);
88+
_word = null;
8389

8490
return 0;
8591
}
8692

93+
static void OnCancelKeyPress(object? sender, ConsoleCancelEventArgs e)
94+
{
95+
if (_word == null)
96+
{
97+
return;
98+
}
99+
100+
try
101+
{
102+
_word.Quit(SaveChanges: false);
103+
Marshal.ReleaseComObject(_word);
104+
}
105+
catch
106+
{
107+
// Word may already be closed
108+
}
109+
110+
_word = null;
111+
}
112+
87113
[LibraryImport("user32.dll")]
88114
internal static partial uint GetWindowThreadProcessId(IntPtr hWnd, out int processId);
89115
}

0 commit comments

Comments
 (0)