VB.NET中如何判断外部启动的Word程序何时关闭?
解决VB.NET监听Word文档关闭的两种方案
方案一:通过Process监听进程退出(简单场景)
如果你的需求是确保启动独立的Word进程打开目标文档,且关闭文档时进程随之结束,可通过注册Process的Exited事件实现非阻塞监听:
- 启动Word进程时明确指定
WINWORD.EXE并传入文档路径,避免复用已有Word进程:
Dim wordProcess As New Process() wordProcess.StartInfo.FileName = "WINWORD.EXE" wordProcess.StartInfo.Arguments = "mydoc.docx" ' 必须启用该属性才能触发Exited事件 wordProcess.EnableRaisingEvents = True ' 绑定进程退出事件处理方法 AddHandler wordProcess.Exited, AddressOf WordProcess_Exited wordProcess.Start()
- 编写事件处理逻辑,在进程退出后检查文件大小变化:
Private Sub WordProcess_Exited(sender As Object, e As EventArgs) Dim process As Process = DirectCast(sender, Process) If process.HasExited Then ' 启动前需提前记录原文件大小,这里示例直接获取(实际应在启动前存储) Dim originalSize As Long = New FileInfo("mydoc.docx").Length Dim currentSize As Long = New FileInfo("mydoc.docx").Length If currentSize <> originalSize Then Console.WriteLine("文档已被编辑") Else Console.WriteLine("文档未修改") End If process.Dispose() End If End Sub
注意:若用户在该Word进程中打开其他文档,关闭目标文档时进程不会退出,此场景下该方案不适用。
方案二:通过Office Interop监听文档关闭(精准场景)
如果需要精准监听目标文档本身的关闭事件(不受Word进程复用影响),推荐使用Office Interop库:
先在项目引用中添加
Microsoft.Office.Interop.Word(选择COM组件中的Microsoft Word xx.x Object Library)编写代码打开文档并绑定关闭事件:
Imports Microsoft.Office.Interop.Word Imports System.Runtime.InteropServices ' 声明全局对象避免被GC提前回收 Private wordApp As Application Private targetDoc As Document Private originalFileSize As Long Private Sub OpenTargetDocument() ' 提前记录原文件大小 originalFileSize = New FileInfo("mydoc.docx").Length wordApp = New Application() wordApp.Visible = True ' 打开目标文档 targetDoc = wordApp.Documents.Open("mydoc.docx") ' 绑定文档关闭事件 AddHandler targetDoc.CloseEvent, AddressOf TargetDoc_Closed End Sub Private Sub TargetDoc_Closed(ByVal SaveChanges As Integer, ByVal OriginalFormat As Integer, ByVal RouteDocument As Integer) ' 检查文件大小变化 Dim currentSize As Long = New FileInfo("mydoc.docx").Length If currentSize <> originalFileSize Then Console.WriteLine("文档已被编辑") Else Console.WriteLine("文档未修改") End If ' 释放COM资源,避免Word进程残留 targetDoc.Close() wordApp.Quit() Marshal.ReleaseComObject(targetDoc) Marshal.ReleaseComObject(wordApp) targetDoc = Nothing wordApp = Nothing End Sub
注意:使用Interop时需确保正确释放COM对象,同时要求用户机器安装对应版本的Office。
内容的提问来源于stack exchange,提问作者John
相关产品推荐
相关产品推荐

