Powershell取消按钮不具有呼叫功能

时间:2016-02-16 14:56:04

标签: powershell checkbox event-handling

我有创建带复选框弹出窗口的脚本。

如果选中复选框并按下确定,则$ districtArray [1]为True

BUT

如果选中复选框并按下CANCEL,则$ districtArray [1]也为真

我希望CANCEL按钮会使整个$ districtArray为FALSE。

因此,当单击CANCEL时,我包含了函数initArray

$CancelButton.Add_Click({initArray; $Form.Close()})

这是完整的脚本供参考

$i = $NULL
$districtArray = @()
$highestDistrict = 33




function initArray{
    for ($i = 0; $i -lt $highestDistrict; $i++) 
    { 
       $script:districtArray += @($false) 
    }


}



function checkbox_test{
    [void] [System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms")
    [void] [System.Reflection.Assembly]::LoadWithPartialName("System.Drawing")

    # Set the size of your form
    $Form = New-Object System.Windows.Forms.Form
    $Form.width = 500
    $Form.height = 200
    $Form.Text = ”Select District”

    # Set the font of the text to be used within the form
    $Font = New-Object System.Drawing.Font("Times New Roman",12)
    $Form.Font = $Font

    # create your checkbox 
    $checkbox1 = new-object System.Windows.Forms.checkbox
    $checkbox1.Location = new-object System.Drawing.Size(30,30)
    $checkbox1.Size = new-object System.Drawing.Size(250,50)
    $checkbox1.Text = "01"
    $checkbox1.Checked = $false
    $Form.Controls.Add($checkbox1)  

    # Add an OK button
    $OKButton = new-object System.Windows.Forms.Button
    $OKButton.Location = new-object System.Drawing.Size(130,100)
    $OKButton.Size = new-object System.Drawing.Size(100,40)
    $OKButton.Text = "OK"
    $OKButton.Add_Click({$Form.Close()})
    $form.Controls.Add($OKButton)

    #Add a cancel button
    $CancelButton = new-object System.Windows.Forms.Button
    $CancelButton.Location = new-object System.Drawing.Size(255,100)
    $CancelButton.Size = new-object System.Drawing.Size(100,40)
    $CancelButton.Text = "Cancel"
    $CancelButton.Add_Click({initArray; $Form.Close()})
    $form.Controls.Add($CancelButton)

    ###########  This is the important piece ##############
    #                                                     #
    # Do something when the state of the checkbox changes #
    #######################################################
    $checkbox1.Add_CheckStateChanged({
    if ($checkbox1.Checked){$districtArray[1] = $true} })


    # Activate the form
    $Form.Add_Shown({$Form.Activate()})
    [void] $Form.ShowDialog() 
}



initArray

#Call the function
checkbox_test


write-host "Value of districtArray[1] is" $districtArray[1]

0 个答案:

没有答案