0

我需要识别当前正在运行的 Excel 进程 ID,以便将其与其他 Excel 进程 ID 进行比较,以便删除其他非当前 Excel 进程。这是我所拥有的,但没有一个进程 ID = 当前 ID。我究竟做错了什么?

Declare Function GetCurrentProcessId Lib "kernel32" () As Int32

Private Sub CheckMemory()
    Dim process As Process
    Dim xlProcessCount = process.GetProcessesByName("EXCEL").Count()
    Dim curProc As IntPtr = GetCurrentProcessId()
    Dim currentProcess As Process = process.GetProcessById(curProc)


    If xlProcessCount > 1 Then
        '            MsgBox("There are " + xlProcessCount + "Excel processes running", MsgBoxStyle.Information)

        'Associate the current active "Excel.exe" process with this application instance 
        'and delete the other running processes

        Dim current = process.GetCurrentProcess()
        For Each process In process.GetProcessesByName("EXCEL")
            If process.Id <> currentProcess.Id Then
                MsgBox("Deleting a previous running Excel process", MsgBoxStyle.Information)

                process.Kill()

                '                    releaseObject(xlApp)
                '                    releaseObject(xlWb)
                '                    releaseObject(xlWs)

            End If
        Next

    End If
4

1 回答 1

0

要直接回答您的问题,您的代码“不起作用”,因为您的流程不是 Excel 流程。返回的进程 IDGetCurrentProcessId()是您的 EXE 的 ID,它不是 Excel。所有 Excel 实例(甚至是由您的应用程序启动的)都是不同的进程,因此它们的进程 ID 永远不会与您的进程 ID 匹配。

现在回答您的问题 - 您需要做的是确保正确清理 Excel 实例。

最好的方法是根本不自动化 Excel,而是使用可以创建 Excel 文件的库。有关一些示例,请参阅此问题的答案:从 C# 创建 Excel (.XLS 和 .XLSX) 文件

如果出于某种原因需要使用 Excel,则必须确保清理 Excel 应用程序返回的每个对象。一般规则是:

  1. 永远不要在调用中使用超过.- 您将需要存储对 Excel 返回的每个对象的引用。
  2. 用于Marhsal.ReleaseObject手动释放所有 Excel COM 对象。

请参阅此问题如何正确清理 Excel 互操作对象?更多细节。

于 2013-06-11T18:16:37.927 回答