如何在 PowerShell 中使用 button.add_click 函数更新或刷新组合框项目?

How to update or refresh comboBox item with button.add_click function in PowerShell?

我使用 ComboBox 来获取目录。我需要使用 Button.Click 事件更新目录。

Add-Type -AssemblyName System.Windows.Forms
[System.Windows.Forms.Application]::EnableVisualStyles()

$Form                            = New-Object system.Windows.Forms.Form
$Form.ClientSize                 = '400,400'
$Form.TopMost                    = $false

$ComboBox1                       = New-Object system.Windows.Forms.ComboBox
$ComboBox1.width                 = 100
$ComboBox1.height                = 20
$ComboBox1.location              = New-Object System.Drawing.Point(36,60)
$ComboBox1.Font                  = 'Microsoft Sans Serif,10'
$list = @(Get-ChildItem -Directory ".\").Name
foreach ($lst in $list) {
    $ComboBox1.Items.Add($lst)
}
$Button1                         = New-Object system.Windows.Forms.Button
$Button1.text                    = "update"
$Button1.width                   = 60
$Button1.height                  = 30
$Button1.location                = New-Object System.Drawing.Point(182,60)
$Button1.Font                    = 'Microsoft Sans Serif,10'
$Button1.Add_Click({
})

$Form.controls.AddRange(@($ComboBox1,$Button1))
$Form.ShowDialog()

您正在使用此填充 ComboBox...

$list = @(Get-ChildItem -Directory ".\").Name
foreach ($lst in $list) {
    $ComboBox1.Items.Add($lst)
}

听起来像您想单击 Button 再次执行此操作,这样 ComboBox 将包含最新的目录列表.在那种情况下,您的 Click 事件处理程序应该像这样创建...

$Button1.Add_Click({
    # Remove all items from the ComboBox
    $ComboBox1.Items.Clear()

    # Repopulate the ComboBox, just like when it was created
    $list = @(Get-ChildItem -Directory ".\").Name
    foreach ($lst in $list) {
        $ComboBox1.Items.Add($lst)
    }
})

Clear() 首先被调用,这样您就不会得到重复的目录项。

顺便说一句,你可以简化这个...

$list = @(Get-ChildItem -Directory ".\").Name
foreach ($lst in $list) {
    $ComboBox1.Items.Add($lst)
}

...到此...

$list = @(Get-ChildItem -Directory ".\").Name
$ComboBox1.Items.AddRange($list)

...甚至这个...

$ComboBox1.Items.AddRange(@(Get-ChildItem -Directory ".\").Name)