【发布时间】:2017-05-22 02:17:50
【问题描述】:
我正在寻找一种更好的编码方式,以便在我的应用程序中正确关闭 WINWORD.EXE 或 word 进程,方法是获取其 PID(进程 ID),就像在 Excel 中获取 PID 一样。
这是我使用 Hwnd 属性和 GetProcessID 类获取 Excel PID 的示例。
Imports System.Diagnostics
Private Declare Function GetWindowThreadProcessId Lib "user32" (ByVal hWnd As Integer, ByRef lpdwProcessId As IntPtr) As IntPtr
Public Sub CreateNewFromTemplate_Excel()
' Create Excel Application, Workbook, and WorkSheets
Dim xlExcel As Excel.Application = New Excel.Application
'Getting the process ID of excel application
Dim processId As IntPtr = Nothing
GetWindowThreadProcessId(xlExcel.Hwnd, processId)
Dim excelProcess As Process = Process.GetProcessById(processId.ToInt32())
Dim blError As Boolean = False
Try
[Perform Excel generation here.]
' Make sure all objects are disposed
xlBook.Close()
xlExcel.Quit()
Catch ex As Exception
blError = True
If Not excelProcess.HasExited Then excelProcess.Kill() ' End the specific Excel Process ID if not yet closed.
Throw
Finally
If Not blError Then
If Not excelProcess.HasExited Then excelProcess.Kill() ' End the specific Excel Process ID if not yet closed.
End If
End Try
End Sub
这是我用于关闭 Word Process/WINWORD.EXE 的代码,但不幸的是,它在服务器端不起作用,因此我正在寻找一种方法和代码来获取 Word Process ID 以正确关闭它。
Marshal.ReleaseComObject(rng)
Dim strFileName As String = comm.GenerateFilename(strUser_Id, strVPN) & ".docx"
' Save the document.
Dim filename As Object = Path.GetFullPath(strNewFilePath & strFileName)
newDoc.SaveAs(FileName:=filename)
' Close.
Dim save_changes As Object = False
newDoc.Close(save_changes)
WordApp.Quit(save_changes)
Marshal.ReleaseComObject(newDoc)
Marshal.ReleaseComObject(WordApp)
rng = Nothing
newDoc = Nothing
WordApp = Nothing
' Let GC know about it
GC.Collect()
GC.WaitForPendingFinalizers()
GC.Collect()
GC.WaitForPendingFinalizers()
' save the file to database
SaveFormat(filename, strUser_Id, strFamilyId.Trim, strVPN.Trim, DateTime.Now.ToString(), "application/vnd.ms-word", br_id, "doc")
If File.Exists(filename) Then
File.Delete(filename)
End If
任何人都可以建议关于如何获取 Word 实例的 PID 或 Hwnd 属性的最佳编码方式或最佳实践。谢谢:)
【问题讨论】:
-
在此处查看this,它是一本好书,您会找到答案的。
-
我居然遇到了这个帖子。我不太了解编写的代码,但我会再试一次,我希望它会起作用。顺便谢谢:)
标签: asp.net vb.net ms-word interop hwnd