Dear forum,
I have an issue, which I hope, you guys can help me with:
I am having a window, named “$objForm”
$objForm = New-Object System.Windows.Forms.Form
in which I have implemented a button (called $btn5). By pushing this button, a function (called done) shall be opened, which generates a “close/done-button” to this form (This works fine, as long, as the code is not outsourced as a function)
in the main window, I have set
$WindowName ='objForm'
to call the function (when pushing the button), I have
$btn5.add_Click{(done $WindowName)}
The function looks like this :
function done
{
param ($WindowName)
$done = New-Object System.Windows.Forms.Button
$doneFont = New-Object System.Drawing.Font("Calibri",18,[System.Drawing.FontStyle]::Bold)
$done.Font = $doneFont
$done.Location = New-Object System.Drawing.Size(320,200)
$done.Size = New-Object System.Drawing.Size(150,50)
$done.ForeColor="red"
$done.Text = "DONE!"
write-host 'Hello'
write-host $WindowName
$WindowName
$done.Add_Click({
$WindowName.Controls.Remove($done),
$WindowName.Controls.refresh()
})
$WindowName.Controls.Add($done)
}
When running the program (the main window), and pushing the button, I get the following:
Hello objForm you cannot call a method on a null-valued expression. At C:\temp\done.ps1:22 char:1 +WindowName.Controls.Add($done) + +CategoryInfo : InvalidOperation: (:) [], RuntimeException +Fully QualifiedErrorID: InvokeMethodOnNull
What I do not understand is: Why can I do a ==> write-Host $WindowName <== in the function
But a ==> $WindowName.Controls.Add($done) <== does not work in the function?
Thank you very much for any help
newbi