为什么在任务管理器中,当我关闭Form1但Outlook进程没有时,Excel进程不存在?

时间:2017-04-05 02:23:45

标签: vb.net excel-interop

  1. 运行以下代码并检查任务管理器以查看Excel和Outlook进程是否存在:

    Imports Microsoft.Office.Interop
    
    Public Class Form1
    
        Private Sub Form1_Load(sender As Object, e As System.EventArgs) Handles Me.Load
    
            'Kill all EXCEL.EXE's from Task Manager
            For Each prog As Process In Process.GetProcessesByName("EXCEL")
                prog.Kill()
            Next
    
            'Kill all OUTLOOK.EXE's from Task Manager
            For Each prog As Process In Process.GetProcessesByName("OUTLOOK")
                prog.Kill()
            Next
    
            'Open new EXCEL.EXE in the Task Manager
            Dim xlApp As New Excel.Application
    
            'Open new OUTLOOK.EXE in the Task Manager
            Dim olApp As New Outlook.Application
    
        End Sub
    
    End Class
    
  2. 关闭Form1

  3. 检查您的任务管理器,看到Excel进程不存在,但Outlook进程确实存在。

  4. 为什么在任务管理器中,当我关闭Form1但Outlook进程没有时,Excel进程不存在?

2 个答案:

答案 0 :(得分:0)

尝试像这样启动Excel:

Dim xlApp As New Process
xlApp.StartInfo.FileName = "filePath/excel.exe"
xlApp.Start

如果有帮助,只需尝试启动exe:

Process.Start("filePath\excel.exe")

答案 1 :(得分:0)

我还没有能够重现您遇到的这个问题。 Outlook进程确实需要更长时间才能结束,但 结束。

话虽如此,还有更好方法来关闭这些流程。如我的评论中所述,请查看此answer链接到Siddharth Rout'scode位。

首先,您需要在班级声明xlAppolApp。您还需要在代码中添加以下方法:

Private Sub ReleaseObject(ByVal obj As Object)
    Try
        Dim intRel As Integer = 0
        Do
            intRel = System.Runtime.InteropServices.Marshal.ReleaseComObject(obj)
        Loop While intRel > 0
        obj = Nothing
    Catch ex As Exception
        obj = Nothing
    Finally
        GC.Collect()
    End Try
End Sub

然后,您可以在关闭表单时调用此方法:

Private Sub Form1_FormClosing(sender As Object, e As FormClosingEventArgs) Handles Me.FormClosing
    xlApp.Quit()
    ReleaseObject(xlApp)

    olApp.Quit()
    ReleaseObject(olApp)
End Sub

总体而言,您的代码看起来与此类似:

Public Class Form1

    Private xlApp As Excel.Application
    Private olApp As Outlook.Application

    Private Sub Form1_Load(sender As Object, e As System.EventArgs) Handles Me.Load

        'Open new EXCEL.EXE in the Task Manager
        xlApp = New Excel.Application

        'Open new OUTLOOK.EXE in the Task Manager
        olApp = New Outlook.Application

    End Sub

    Private Sub Form1_FormClosing(sender As Object, e As FormClosingEventArgs) Handles Me.FormClosing
        xlApp.Quit()
        ReleaseObject(xlApp)

        olApp.Quit()
        ReleaseObject(olApp)
    End Sub

    Private Sub ReleaseObject(ByVal obj As Object)
        Try
            Dim intRel As Integer = 0
            Do
                intRel = System.Runtime.InteropServices.Marshal.ReleaseComObject(obj)
            Loop While intRel > 0
            obj = Nothing
        Catch ex As Exception
            obj = Nothing
        Finally
            GC.Collect()
        End Try
    End Sub

End Class