1

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 :)

YowE3K
  • 23,852
  • 7
  • 26
  • 40
chobowski
  • 109
  • 1
  • 13
  • 1
    Check out [**this**](http://stackoverflow.com/questions/814936/get-pid-from-ms-word-applicationclass) here, its a good read and you'll find your answer. – Trevor May 22 '17 at 04:48
  • I actually encounter this post. I don't understand much of the code written but I'll try this again and I hope it will work. Thanks by the way :) – chobowski May 23 '17 at 00:16

1 Answers1

-1

What you are trying to do is probably not going to work as reliably as expected. I would strongly suggest that you switch to OpenXML or some other library if you need to process documents and spreadsheets from Server side.

I tend to use EPPlus which works very well and is almost the same code as VBA/Interop. http://epplus.codeplex.com/

I would read the following warnings and articles from Microsoft before proceeding:

All current versions of Microsoft Office were designed, tested, and configured to run as end-user products on a client workstation. They assume an interactive desktop and user profile. They do not provide the level of reentrancy or security that is necessary to meet the needs of server-side components that are designed to run unattended.

Microsoft does not currently recommend, and does not support, Automation of Microsoft Office applications from any unattended, non-interactive client application or component (including ASP, ASP.NET, DCOM, and NT Services), because Office may exhibit unstable behavior and/or deadlock when Office is run in this environment.

https://support.microsoft.com/en-us/help/257757/considerations-for-server-side-automation-of-office

Jason Bayldon
  • 1,296
  • 6
  • 24
  • 41
  • `What you are trying to do is not going to work.`, this is a ludacris statement. I can prove this statement to be wrong, what case can you provide that validates your statement? Please inform us? – Trevor May 23 '17 at 01:54
  • @Zaggler Was the official Microsoft link not enough? This process will not be reliable and is clearly not best practice. If OP truly wants to implement Interop on ASP.NET that is his prerogative but clearly according to Microsoft he should steer clear for a variety of reasons. I am sure there are many Stack Overflow articles on the same. – Jason Bayldon May 23 '17 at 15:31
  • I understand and agree about `best practice`, but you have not answered my question. Can you provide a clear test case as to ***why this is not going to work?*** So far I have not seen one. – Trevor May 23 '17 at 15:33
  • @Zaggler I edited my answer because the process may work, but is it going to work reliably? No one here is going to have the answer to that due to the variability. I don't have a clear test-case but there are numerous reported issues with using Interop unattended on SO. Do the research. That to me is as good as it "not working". OP should be steering clear entirely as there are far better methods for generating spreadsheets on a server. – Jason Bayldon May 23 '17 at 15:51