Search code examples
.netvb.nettasklist

How do you update a ListBox with running processes in real-time?


In Windows, the Task Manager updates itself automatically with all of the running processes on your Laptop/Desktop. However, that is not my point.

My question is, is there a way to update a ListBox (Preferably with Timer1.Tick due to my instance) with all new processes, but in real-time (updates to the new processes every set interval)?

I have my ListBox1 filled with the currently running processes.

Things I've Tried

  1. In my sub 'Timer1_Tick', I've tried using the ListBox1.Refresh() code, but, I've realised, all that does is refresh the ListBox, not the running process.

  2. Researching for similar questions

Code that gets the running processes

Private Sub Mainframe_Load(sender As Object, e As EventArgs) Handles MyBase.Load

        Dim procs() As System.Diagnostics.Process = System.Diagnostics.Process.GetProcesses
        Dim f As String

        For Each proc As System.Diagnostics.Process In procs
            f = GetProcessFileName(proc)
            If f.Length > 0 Then
                ListBox1.Items.Add(f)
                ListBox1.Items.Add("MD5: " & GetMD5String(f)) <-- Not relevant
                ListBox1.Items.Add(String.Empty)
            End If

        Next

    End Sub

My Timer1 code

Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
    Timer1.Enabled = False 'Stops the timer
    ListBox1.Update()
    ListBox1.Refresh()
    Timer1.Enabled = True
End Sub

Solution

  • From the top of my head: it should be something like this.

    Disclaimer: I speak not so good VB ;-)

    PS: possibly you get a "not on the same thread invoke exception"

    Private Sub Mainframe_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        'call it initially
        RefreshList()
    End Sub
    
    'this sub actually does the lisbox update
    Private Sub RefreshList()
        Dim procs() As System.Diagnostics.Process = System.Diagnostics.Process.GetProcesses
        Dim f As String
    
        'as from @Visual Vincent's comment:
        ListBox1.BeginUpdate()
        ListBox.Items.Clear()
    
        For Each proc As System.Diagnostics.Process In procs
            f = GetProcessFileName(proc)
            If f.Length > 0 Then
                ListBox1.Items.Add(f)
                ListBox1.Items.Add("MD5: " & GetMD5String(f)) <-- Not relevant
                ListBox1.Items.Add(String.Empty)
            End If
    
        Next
    
        ListBox1.EndUpdate()
    
    End Sub
    
    Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
        Timer1.Enabled = False 'Stops the timer
        RefreshList()
        Timer1.Enabled = True
    End Sub