Datta Deshmukh

Datta Deshmukh

  • NA
  • 1
  • 2.4k

getwindowthreadprocessid returns 0 for Excel process

Sep 4 2015 8:42 AM

Problem - In windows service we are creating excel object and after that killing that Excel object. However everytimegetwindowthreadprocessid method returns 0 and process cannot be killed. We need to kill only specific instance of that process so we cannot use GetProcessByName.

If i select Local user account and check "Allow service to interact with desktop" it works for me. However we do not want local account to be used.

Solutions tried :

1) We have added desktop folder in c:\windows\system32\Config\systemprofile\desktop and given full control to account we are using -Not worked

2) We have given permission to access userdll32.dll to user accont we are using.Not worked

code

Private Sub KillExcelProcess(ByRef xlApp As Excel.Application)       

                xlApp.Quit()
                GetWindowThreadProcessId(CType(hwnd, IntPtr), excelProcessId)
  Dim procs As Process() = Process.GetProcessesByName("EXCEL")

                For Each p As Process In procs
                    If p.Id = excelProcessId Then
                        p.Kill() 
                    End If
                Next
                Marshal.FinalReleaseComObject(xlApp)
            End If
 
< DllImport("user32.dll", SetLastError:=True)> _

        Private Shared Function GetWindowThreadProcessId(ByVal hwnd As IntPtr, _

                                         ByRef lpdwProcessId As Integer) As Integer


        End Function