count and display the number of clicks on a label using PowerShell

38 Views Asked by At

I want to count and display the number of clicks on a label using PowerShell in a graphical user interface (GUI). This is my script:

 Add-Type -AssemblyName System.Windows.Forms

# Create form
$form = New-Object Windows.Forms.Form
$form.Text = "Click Counter"
$form.Size = New-Object Drawing.Size(300,150)

# Create label
$label = New-Object Windows.Forms.Label
$label.Text = "Click Count: 0"
$label.AutoSize = $true
$label.Location = New-Object Drawing.Point(20,20)

# Create button
$button = New-Object Windows.Forms.Button
$button.Text = "Click Me"
$button.Location = New-Object Drawing.Point(20,60)


$button.Add_Click({
    $clickCount++
    $label.Text = "Click Count: $clickCount"
})

# Add controls to the form
$form.Controls.Add($label)
$form.Controls.Add($button)

# Initialize click count
$clickCount = 0

# Show the form
$form.ShowDialog()

but the problem that i can't increament the number in label and it s fixed in number "1"

1

There are 1 best solutions below

0
Santiago Squarzon On

You need to increment your counter variable using the script: scope modifier otherwise a new $clickCount variable is declared and incremented in the event handler scope and its value is lost as soon as the event completes:

$clickCount = 0
$button.Add_Click({
    $script:clickCount++
    $label.Text = "Click Count: $clickCount"
})

Another alternative is to use a reference type, for example an array:

$clickCount = @(0)
$button.Add_Click({
    $clickCount[0]++
    $label.Text = "Click Count: $clickCount"
})