Wednesday, March 14, 2012

VB.Net kill process by name

 .Net made it very easy for handling processes. It is much easier to close the applications using Process.Kill(). Processes can be iterated using the ‘for each’ loop. The process object taken from enumeration has enough methods and properties to deal with processes.

To get the list of instances running with the current applications name, we can use the Process.GetProcessesByName(“ProcessName”). This method returns collection of processes with the name “ProcessName”.  Thereafter accessing each process is easy with a ‘for each’ loop.

I had a requirement to ensure that, current process is the only running process. The rest of the other instances of the processes have to be closed. Using the GetProcessesByName method we can get the list of current instances. While iterating thro the collection, we can identify the current process by the ID property. We can get the current running process by Process.GetCurrentProcess(). Now it is very easy to kill other process than the current one.

Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles Button1.Click
For Each RunningProcess In Process.GetProcessesByName("Notepad")
RunningProcess.Kill()
Next
End Sub
Private Sub Form1_Load(ByVal sender As Object, _
ByVal e As System.EventArgs) Handles Me.Load
For Each RunningProcess In Process.GetProcessesByName(Process.GetCurrentProcess().ProcessName)
If (Not RunningProcess.Id = Process.GetCurrentProcess().Id) Then
RunningProcess.Kill()
End If
Next
End Sub
End Class

View the original article here

No comments:

Post a Comment