user2016392
user2016392

Reputation:

Closing multiple programs with the same name

One part of my program is to close another program or the same program with the same name... I looked up how to do this and got this code:

Dim myprocesses() As Process
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
  For Each p As Process In myprocesses
    If p.MainWindowTitle.Contains("notepad") Then
      p.CloseMainWindow()
    End If
  Next
End Sub

It should work, however when I run it I'm getting an error message on the Next statement saying:

{"Object reference not set to an instance of an object."}

Does anyone know what's wrong with the above code?

UPDATE: Some of these answers seem to work :) Thanks. However there is a slight problem because sometimes the program doesn't load up until about 30 seconds (notepad was just put there for simplicity) so I need the code to close the PROCESS and not the actual program when it loads.

Hope you can understand that xD ^^^^

Upvotes: 2

Views: 302

Answers (2)

Pandian
Pandian

Reputation: 9126

Try below code in your button click event:

Dim myProc As System.Diagnostics.Process
For Each myProc In System.Diagnostics.Process.GetProcesses
  Console.WriteLine(myProc.MainWindowTitle)
  If myProc.MainWindowTitle.ToUpper.Contains("NOTEPAD") Then
    myProc.CloseMainWindow()
  End If
Next

Upvotes: 1

spajce
spajce

Reputation: 7082

Obviously you declared the myprocesses() but null, so to achieve your task you must use GetProcessesByName

For Each process1 As Object In Process.GetProcessesByName("Notepad")
    process1.Kill()
Next

But here's the proper way to manage the .exe process.

Upvotes: 2

Related Questions