CodeCatia
CodeCatia

Reputation: 127

Kill last created Excel instance in task manager vb.net

Can you help me solve my problem?

I have couple instances of Excel opened (EXCEL.EXE in task manager) and I want to kill last opened instance. For now i can kill first instance, but i want to kill last:

Sub Main()
    Dim dictExe As Object
    dictExe = CreateObject("Scripting.Dictionary")

    Dim oServ As Object
    Dim cProc
    Dim oProc As Object
    oServ = GetObject("winmgmts:")
    cProc = oServ.ExecQuery("Select * from Win32_Process")
    For Each oProc In cProc
        If oProc.Name = "EXCEL.EXE" Then
            dictExe.Add(oProc, oProc.CreationDate)
        End If
    Next

    For Each oProcCatia In dictExe
        If oProcCatia.Name = "EXCEL.EXE" Then
            Dim errReturnCode
            errReturnCode = oProcCatia.Terminate()
            Exit Sub
        End If
    Next
End Sub

i was thinking to kill instance in dictionary witch have largest creation date but I don't know how. So question can also be, how to get key with largest value from dictionary?

Upvotes: 0

Views: 368

Answers (1)

Forty3
Forty3

Reputation: 2229

I would forgo the use of the Scripting.Dictionary and simply keep a reference of the latest CreationDate:

Sub Main()
    Dim oServ As Object
    Dim cProc
    Dim oProc As Object
    Dim oToBeRemovedProc As Object
    Dim oToBeRemovedCreationDate As Object

    oServ = GetObject("winmgmts:")
    cProc = oServ.ExecQuery("Select * from Win32_Process")
    For Each oProc In cProc
        If oProc.Name = "EXCEL.EXE" Then
            '::: No good checking values against Nothing
            If oToBeRemovedProc Is Nothing Then
                oToBeRemovedProc = oProc
                oToBeRemovedCreationDate = oProc.CreationDate
            End If

            '::: Is the current hold value older than this one?
            If oToBeRemovedCreationDate < oProc.CreationDate Then
                oToBeRemovedProc = oProc
                oToBeRemovedCreationDate = oProc.CreationDate
            End If
        End If
    Next

    '::: Do we actually have something to remove?
    If Not oToBeRemovedProc Is Nothing Then
        oToBeRemovedProc.Terminate()
        oToBeRemovedProc = Nothing
        oToBeRemovedCreationDate = Nothing 
    End If
End Sub

Upvotes: 1

Related Questions