【发布时间】:2016-03-17 20:32:33
【问题描述】:
我正在开发一个 Word 自动化工具,我在 WPF 窗口中托管 Word。我使用下面的代码来创建一个新的 Word 应用程序
// Initialize handle value to invalid
appWin = IntPtr.Zero;
// Start the remote application
try
{
// Start the process
if (_wordApp == null) _wordApp = new ApplicationClass();
_wordApp.Application.Caption = WORD_APP_NAME;
//find the process
appWin = FindWindow("Opusapp", _wordApp.Application.Caption);
}
catch (Exception ex)
{
MessageBox.Show(this, ex.Message, "Error");
}
// Put it into this form
SetParent(appWin, this.Handle);
在关闭应用程序时,我希望杀死所有生成的 Word 应用程序。
protected override void OnHandleDestroyed(EventArgs e)
{
// Stop the application
if (appWin != IntPtr.Zero)
{
// to be sure that the word app closes without trace
try
{
uint pid;
uint pid2 = GetWindowThreadProcessId(appWin,out pid);
Process proc = Process.GetProcessById((int)pid);
proc.Kill();
}
catch (Exception)
{
//write logs.
}
_wordApp = null;
// Clear internal handle
appWin = IntPtr.Zero;
}
base.OnHandleDestroyed (e);
}
问题是当用户使用这个应用程序并并行打开一个新的 Word 文档时,新的 Word 充当当前进程的子进程,因此在终止进程时,新的 Word 应用程序也会关闭。
如何确保我使用的 Word 应用程序始终与当前运行或稍后打开的任何其他 Word 应用程序不同。
【问题讨论】:
-
你不需要终止进程。保留对您创建的单词 Application 的引用并调用其 Quit 方法就足够了。
-
这个问题还是没有好的答案。我想保留一个专用于该软件的后台进程,因为在该框架中以这种方式使用它会更快,但如果我在外部打开另一个 Word,它会打开内部进程。