Private processesByID As New Dictionary(Of Integer, Process)
Private Sub Form1_Load(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles MyBase.Load
Me.RefreshProcessList()
End Sub
Private Sub Timer1_Tick(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles Timer1.Tick
Me.RefreshProcessList()
End Sub
Private Sub RefreshProcessList()
'Create a dictionary of currently running processes keyed on their ID.
Dim currentProcessesByID = Process.GetProcesses().ToDictionary(Function(p) p.Id)
'Remove processes that are no longer running.
For Each id In Me.processesByID.Keys.ToArray()
If Not currentProcessesByID.ContainsKey(id) Then
'This process is no longer running so destroy the Process object and remove it from the list.
Me.processesByID(id).Dispose()
Me.processesByID.Remove(id)
End If
Next
'Add new processes.
For Each id In currentProcessesByID.Keys
If Me.processesByID.ContainsKey(id) Then
'This process is already in the list so destroy the duplicate.
currentProcessesByID(id).Dispose()
Else
'This is a new process so add it to the list.
Me.processesByID.Add(id, currentProcessesByID(id))
End If
Next
'Update the list view.
Me.ListView1.BeginUpdate()
Me.ListView1.Items.Clear()
'Add an item for each current process.
For Each id In Me.processesByID.Keys
Me.ListView1.Items.Add(id.ToString()).SubItems.Add(Me.processesByID(id).ProcessName)
Next
Me.ListView1.EndUpdate()
End Sub