I'm looking for a better way of coding for proper closing of WINWORD.EXE or word process in my application by getting its PID (Process ID) just like getting the PID in Excel.
This is my sample of getting the PID of an Excel using Hwnd property and GetProcessID class.
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
This is my code for closing the Word Process/WINWORD.EXE but unfortunately, it's not working on the server side so I'm looking for a way and code to get the Word Process ID to properly close it.
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
Can anyone suggest what's the best way or the best practice for coding on how to get the PID or Hwnd property of Word instance. Thanks :)