3

I'm struggling here.

Using Powershell and GUI, how to automatically refresh data on a form?

Example with the script below, how to automatically update the label with the number of process executed by my computer?

Add-Type -AssemblyName System.Windows.Forms
$Form = New-Object system.Windows.Forms.Form
$Form.Text = "Sample Form"
$Label = New-Object System.Windows.Forms.Label
$Label.Text = "Number of process executed on my computer"
$Label.AutoSize = $True
$Form.Controls.Add($Label)
$Form.ShowDialog()
Nick32342
  • 93
  • 1
  • 7

1 Answers1

2

You need to add a timer to the form to do the updating for you. Then add the code you need to gather the process count to the .Add_Tick, as shown below:

function UpdateProcCount($Label)
{
    $Label.Text = "Number of processes running on my computer: " + (Get-Process | measure).Count
}

$Form = New-Object System.Windows.Forms.Form
$timer = New-Object System.Windows.Forms.Timer
$timer.Interval = 1000
$timer.Add_Tick({UpdateProcCount $Label})
$timer.Enabled = $True
$Form.Text = "Sample Form"
$Label = New-Object System.Windows.Forms.Label
$Label.Text = "Number of process executed on my computer"
$Label.AutoSize = $True
$Form.Controls.Add($Label)
$Form.ShowDialog()
Eric Walker
  • 1,042
  • 10
  • 15
  • 1
    Please add (at the least) a brief comment about the Timer, it might not be obvious to the untrained eye – Mathias R. Jessen Oct 28 '15 at 17:21
  • Thanks Mathias, added a bit of description regarding the timer and it's Tick event handler. – Eric Walker Oct 28 '15 at 17:50
  • Thank you very much Eric! I've an additional question. If I want a second label showing for example the percentage of CPU usage, how can I update two labels in one function call? – Nick32342 Oct 28 '15 at 20:51
  • Using the example above, just make another variable, $labelCPU for example, and add it to the form like the first label. Then update the function UpdateProceCount to update both label.Text properties. Other than saying that you'll need to pass both label objects as parameters to the function, and a separate statement to update each property, I'll leave the powershell necessary to get the CPU utilization as an exercise for you. – Eric Walker Oct 28 '15 at 22:39
  • Hey Eric, I called a function on a mouse event on the label but since I have added the timer, the events don't work longer. I have posted this here: http://stackoverflow.com/q/33577527/5498995 A little more help would be nice :) – Nick32342 Nov 07 '15 at 22:00
  • Hey guys, I've posted my entire problem here if you're ready to help :) Thx http://stackoverflow.com/questions/33639213/background-job-to-refresh-data-on-a-form-while-script-is-running – Nick32342 Nov 10 '15 at 20:49