如何用PowerShell WinForms创建含多行文件名的选择菜单?
实现PowerShell WinForms单选ListBox加载文件名
下面是完整的实现代码,包含窗体创建、文件名加载、单选设置和选中结果获取:
# 加载WinForms程序集 Add-Type -AssemblyName System.Windows.Forms # 创建主窗体 $form = New-Object System.Windows.Forms.Form $form.Text = "选择文件" $form.Size = New-Object System.Drawing.Size(300, 300) $form.StartPosition = "CenterScreen" # 创建ListBox控件 $listBox = New-Object System.Windows.Forms.ListBox $listBox.Location = New-Object System.Drawing.Point(20, 20) $listBox.Size = New-Object System.Drawing.Size(250, 200) # 设置为单选模式 $listBox.SelectionMode = [System.Windows.Forms.SelectionMode]::One # 你的按行排列的文件名字符串示例 $fileNamesString = @" file1 file2 file3 file4 "@ # 分割字符串为文件名数组,过滤空行 $fileNames = $fileNamesString -split "`n" | Where-Object { $_ -match '\S' } # 批量添加文件名到ListBox(比循环Add更高效) $listBox.Items.AddRange($fileNames) # 创建确认按钮,用于获取选中项 $confirmBtn = New-Object System.Windows.Forms.Button $confirmBtn.Text = "确认选择" $confirmBtn.Location = New-Object System.Drawing.Point(20, 230) $confirmBtn.Size = New-Object System.Drawing.Size(250, 30) $confirmBtn.Add_Click({ # 获取选中的文件名 $selectedFile = $listBox.SelectedItem if ($selectedFile) { [System.Windows.Forms.MessageBox]::Show("你选择了: $selectedFile", "选择结果") $form.Close() } else { [System.Windows.Forms.MessageBox]::Show("请选择一个文件", "提示") } }) # 将控件添加到窗体 $form.Controls.Add($listBox) $form.Controls.Add($confirmBtn) # 显示窗体并等待用户操作 $form.ShowDialog() | Out-Null
关键说明:
- 变量解析问题:你之前用
[void] $listBox.Items.Add('$string')会把$string当成字面量字符串,无法解析变量值,改用数组批量添加的方式更高效。 - 字符串分割处理:用
-split "n"把按行的字符串拆分为数组,再通过Where-Object`过滤空行,避免ListBox出现无效空白项。 - 单选模式设置:通过
$listBox.SelectionMode = [System.Windows.Forms.SelectionMode]::One强制开启单选,符合需求。 - 选中项获取:通过
$listBox.SelectedItem直接读取当前选中的文件名,也可以在窗体关闭后直接调用该属性获取结果。
内容的提问来源于stack exchange,提问作者Ivan Benishek
相关产品推荐
相关产品推荐

