Closing a process problem

kservice

Newcomer
Joined
Jan 13, 2004
Messages
24
Hi There,

I have searched this site for "closing processes" and found some great stuff.

I copied and changed some code that I found and have come up with the following function.

Code:
Public Function PrevInstance() As Boolean
        Dim processes(), p As Process

        Try
            processes = Process.GetProcesses()
            For Each p In processes
                If Not (p.MainModule Is Nothing) Then
                    If System.IO.Path.GetFileName(p.MainModule.FileName).ToLower() = "winword.exe" Then
                        p.Kill()
                        Exit For
                    End If
                End If
            Next p
        Catch ex As Exception
            Throw
        Finally

        End Try

    End Function

The problem is that it works great if it finds what it's looking for. If "Word" is not running than I get the following error:

Run-time exception thrown: System.ComponentModel.Win32Exception - Unable to enumerate the process modules.

I hope it's just something small that I'm missing.

Thanks for your time.
 
you could just change the line that reads
Visual Basic:
throw
to something like
Visual Basic:
MessageBox.Show ("Process not found")
to stop it crashing out. However if you step through the code in the debugger which line is the one it fails on?
 
It fails out on the line:

If Not (p.MainModule Is Nothing) Then

It's like it doesn't know it's reached the end of the processes or something.

Thanks
 
So I have stepped through it some more and at least can dup the error every time.

There are usually 26 processes running when I try this code and I get to process number 23 and it blows on "If Not (p.MainModule Is Nothing) Then".

Help? :rolleyes:
 
Back
Top