【发布时间】:2022-01-27 16:52:16
【问题描述】:
我正在尝试修改 Microsoft 文档 (https://docs.microsoft.com/en-us/powershell/scripting/samples/multiple-selection-list-boxes?view=powershell-7.2) 中的代码以包含 2 个列表框:一个单选和一个多选。
这个问题只是 listBox2 出现了。 到目前为止我所拥有的:
Add-Type -AssemblyName System.Windows.Forms
Add-Type -AssemblyName System.Drawing
$form = New-Object System.Windows.Forms.Form
$form.Text = 'Data Entry Form'
$form.Size = New-Object System.Drawing.Size(600,200)
$form.StartPosition = 'CenterScreen'
$OKButton = New-Object System.Windows.Forms.Button
$OKButton.Location = New-Object System.Drawing.Point(75,120)
$OKButton.Size = New-Object System.Drawing.Size(75,23)
$OKButton.Text = 'OK'
$OKButton.DialogResult = [System.Windows.Forms.DialogResult]::OK
$form.AcceptButton = $OKButton
$form.Controls.Add($OKButton)
$CancelButton = New-Object System.Windows.Forms.Button
$CancelButton.Location = New-Object System.Drawing.Point(150,120)
$CancelButton.Size = New-Object System.Drawing.Size(75,23)
$CancelButton.Text = 'Cancel'
$CancelButton.DialogResult = [System.Windows.Forms.DialogResult]::Cancel
$form.CancelButton = $CancelButton
$form.Controls.Add($CancelButton)
#Single Select Start
$label = New-Object System.Windows.Forms.Label
$label.Location = New-Object System.Drawing.Point(10,20)
$label.Size = New-Object System.Drawing.Size(280,20)
$label.Text = 'Select Primary USB from the list below:'
$form.Controls.Add($label)
$listBox = New-Object System.Windows.Forms.Listbox
$listBox.Location = New-Object System.Drawing.Point(10,40)
$listBox.Size = New-Object System.Drawing.Size(260,20)
#Single Select End
#Multiple Item Select Start
$label2 = New-Object System.Windows.Forms.Label
$label2.Location = New-Object System.Drawing.Point(310,20)
$label2.Size = New-Object System.Drawing.Size(280,20)
$label2.Text = 'Select Secondary USB(s) from the list below:'
$form.Controls.Add($label2)
$listBox2 = New-Object System.Windows.Forms.Listbox
$listBox2.Location = New-Object System.Drawing.Point(310,40)
$listBox2.Size = New-Object System.Drawing.Size(260,20)
$listBox2.SelectionMode = 'MultiExtended'
#Multiple Item Select End
$testArray = gdr
ForEach($n in $testArray){
if(($n.Root.Length -lt 4) -And ($n.Root.Length -gt 0) -And ($n.Root -ne "\") -And ($n.Root -ne "C:\")){
[void] $listBox.Items.Add($n.Root)
[void] $listBox2.Items.Add($n.Root)
}
}
$listBox.Height = 70
$listBox2.Height = 70
$form.Controls.Add($listBox1)
$form.Controls.Add($listBox2)
$form.Topmost = $true
$result = $form.ShowDialog()
if ($result -eq [System.Windows.Forms.DialogResult]::OK)
{
$x = $listBox1.SelectedItem
$y = $listBox2.SelectedItems
Write-Host "Single Item Selected" $x
Write-Host "Multiple Items Selected" $y
}
附:有人可以为 PowerShell-GUI 制作一个新标签
【问题讨论】:
-
在大多数代码中,您使用
$listBox,但随后您调用$form.Controls.Add($listBox1)(注意尾随1)而不是$form.Controls.Add($listBox)- 使用一致的变量名称,它可能会工作:) -
@MathiasR.Jessen 非常感谢,这非常有效。
标签: powershell user-interface listbox