0

I am a newbie to the world of programming and I am trying to create a form using functions to create the buttons and labels etc. The form is created with the exception that the functions passed to on button click events are not being passed correctly. For example I have a function to create a button....

function new_btn ($name, $parent, $x, $y, $l, $h, $text, $onClick){
    $object = New-Object System.Windows.Forms.Button
    $object.Location = New-Object System.Drawing.Point($x, $y)
    $Object.Size = New-Object System.Drawing.Size($l, $h)
    $Object.Text = $text
    $object.add_Click({$onClick})
    New-Variable $name -Value $object -Scope global
    (Get-Variable $parent).Value.Controls.Add((Get-Variable $name).value)
}

I then have the function that I want to run on the button click.....

function msg {
    [System.Windows.Forms.MessageBox]::Show("We are proceeding with next step.") 

}

I then call the function and feed it the parameters.......

new_btn getdbslist tab1 20 50 69 23 "Get DB's" msg

This produces the button as expected and adds it to tab1, but the on click event will not work, nothing happens at all. Any help would be very appreciated!

1 Answer 1

1

You are just passing a string. Instead pass a script block:

new_btn getdbslist tab1 20 50 69 23 'Get DBs' {
  [System.Windows.Forms.MessageBox]::Show("We are proceeding with next step.") 
}

And in your new_btn function you probably just need to use

$object.add_Click($onClick)

If you really want to pass a string, then you probably need to use the following:

$object.add_Click({ & $onClick })
Sign up to request clarification or add additional context in comments.

2 Comments

Side note: Your naming of functions is questionable here. New-Button would be a far more meaningful name, although it should then return a new instance, instead of just adding something to another object. So Add-Button would probably be preferable. And once you go down that path, you should probably use PascalCase parameter names as well and perhaps use a prefix for your function name to avoid clashes with other modules.
Thank you so much Joey, really appreciate such a quick response and hints to improve the code.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.