I'm trying to create a a new Windows Form button with my function that takes few params like size, position, Name and batchFile path that will be run when clicked. When I run it I got lots of errors like: $btnName,Location --> The property 'Location' cannot be found on this object. $btnName.Add_Click({ --> Method invocation failed because [System.String] does not contain a method name 'Add_Click'
I think that I'm passing my $btnName wrong but I don't know how to fix it or replace [string] with?
My idea is that after passing for example "buttonTest" as $btnName it would create a custom button like $buttonTest = New-Object System.Windows.Forms.Button.
Here's the code:
Add-Type -AssemblyName System.Windows.Forms
$Form = New-Object System.Windows.Forms.Form
$Form.Text = "Copy Test"
$Form.Width = 450
$Form.Height = 300
$Form.StartPosition = "CenterScreen"
$Form.FormBorderStyle = 'FixedDialog'
$Form.BackColor = [System.Drawing.Color]::LightBlue
$Form.MaximizeBox = $false
$copyBatch = "test-batch.bat"
Function createBtn {
param (
[string]$btnName,
[string]$btnDesc,
[string]$batchFile,
[int]$sizeW,
[int]$sizeH,
[int]$posX,
[int]$posY
)
# Create a new button
$btnName = New-Object System.Windows.Forms.Button
$btnName.Name = $btnName
$btnName.Text = $btnDesc
$btnName.Width = $sizeW
$btnName.Height = $sizeH
$btnName.Location = New-Object System.Drawing.Point($posX, $posY)
$btnName.Add_Click({
$btnName.Enabled = $false # Disable button when clicked
Start-Process -FilePath $batchFile -Wait # Run batch file and wait for it to finish
$btnName.Enabled = $true # Enable button
})
$Form.Controls.Add($btnName)
}
createBtn -btnName "buttonTest" -btnDesc "Copy All" -batchFile $copyBatch -sizeW 200 -sizeH 40 -posX 200 -posY 50
$Form.ShowDialog() | Out-Null
Thanks for the help, I'm still learning :)