0

This page suggests that creating your handler as a function is best, because it's the only way to pass parameters.

My question is, how would I go about passing parameters to the button handler?

Suppose I want to pass in the current user profile as a parameter and display it when the button is clicked, how can I do that?

Suppose I have this code:

#Pass a parameter to the button function to display current user
Function Button_Click()
{
    [System.Windows.Forms.MessageBox]::Show("Hello World." , "My Dialog Box")
}
Function Generate-Form {

    Add-Type -AssemblyName System.Windows.Forms    
    Add-Type -AssemblyName System.Drawing

    # Build Form
    $Form = New-Object System.Windows.Forms.Form
    $Form.Text = "My Form"
    $Form.Size = New-Object System.Drawing.Size(200,200)
    $Form.StartPosition = "CenterScreen"
    $Form.Topmost = $True

    # Add Button
    $Button = New-Object System.Windows.Forms.Button
    $Button.Location = New-Object System.Drawing.Size(35,35)
    $Button.Size = New-Object System.Drawing.Size(120,23)
    $Button.Text = "Show Dialog Box"

    $Form.Controls.Add($Button)

    #Add Button event 
    $Button.Add_Click({Button_Click})


    #Show the Form 
    $form.ShowDialog()| Out-Null 

} #End Function 

#Call the Function 
Generate-Form

1 Answer 1

4

You already have the function built. You just need to add parameters and pass them when the function is called. A simple param would cover that.

Function Button_Click()
{
    param($text)
    [System.Windows.Forms.MessageBox]::Show("$text" ,"My Dialog Box")
}

And then your function call using the profile environment variable:

#Add Button event 
$Button.Add_Click({Button_Click $env:USERPROFILE})

Depending on how complicated your handler is it might be better to use advanced parameters in your function.

Function Button_Click()
{
    param(
        [parameter(Mandatory=$true)]
        [String]$Text,
        [parameter(Mandatory=$true)]
        [String]$Title
    )
    [System.Windows.Forms.MessageBox]::Show($text ,$Title)
}


#Add Button event 
$Button.Add_Click({Button_Click -Text $env:USERPROFILE -Title "My Dialog Box"})
Sign up to request clarification or add additional context in comments.

1 Comment

Is it proper practice to call the Button_Click elsewhere in my code? For example, lets say I have to text fields and I allow the user to enter two numbers, and when they click the button, those two numbers get added and the result is show in the Mesagebox. Could I call the button_click function elsewhere in my code?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.