4

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()

1 Answer 1

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()
Sign up to request clarification or add additional context in comments.

6 Comments

Please add (at the least) a brief comment about the Timer, it might not be obvious to the untrained eye
Thanks Mathias, added a bit of description regarding the timer and it's Tick event handler.
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?
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.
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: stackoverflow.com/q/33577527/5498995 A little more help would be nice :)
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.