#WinForms 图形界面
WinForms 是 .NET 的桌面 UI 框架。PowerShell 可以加载 System.Windows.Forms,快速创建窗口、按钮和事件处理程序。
#加载程序集
使用 Add-Type -AssemblyName 加载程序集:
> Add-Type -AssemblyName System.Windows.Forms
> Add-Type -AssemblyName System.Drawing
System.Drawing 提供 Point、Size、Font 等类型,创建控件时经常用到。
#创建窗体
form.ps1
Add-Type -AssemblyName System.Windows.Forms
Add-Type -AssemblyName System.Drawing
$form = New-Object System.Windows.Forms.Form
$form.Text = '示例窗口'
$form.Size = New-Object System.Drawing.Size(400, 220)
$form.StartPosition = 'CenterScreen'
$label = New-Object System.Windows.Forms.Label
$label.Text = '请输入内容:'
$label.Location = New-Object System.Drawing.Point(20, 20)
$label.AutoSize = $true
$form.Controls.Add($label)
$textBox = New-Object System.Windows.Forms.TextBox
$textBox.Location = New-Object System.Drawing.Point(20, 50)
$textBox.Width = 340
$form.Controls.Add($textBox)
$button = New-Object System.Windows.Forms.Button
$button.Text = '确定'
$button.Location = New-Object System.Drawing.Point(20, 90)
$button.Add_Click({
[System.Windows.Forms.MessageBox]::Show("你输入了:$($textBox.Text)")
})
$form.Controls.Add($button)
$form.ShowDialog()
Controls.Add把控件加入窗体。- 控件的坐标通过
Location设置,单位是像素。 AutoSize让标签根据内容自动调整大小。
#事件处理
通过 Add_Click、Add_TextChanged 等方法注册事件,参数是一个脚本块:
$button.Add_Click({
$this.Enabled = $false
[System.Windows.Forms.MessageBox]::Show('处理完成')
})
- 在事件脚本块中,
$this指向触发事件的控件。 - 可以通过
$button、$textBox等变量访问窗体中的其他控件。 - 耗时操作不要直接放在事件中,否则界面会卡住。
#ShowDialog 与 Show
ShowDialog() 以 模态 方式显示窗口:窗口关闭前,调用它的脚本会一直等待。
> $form.ShowDialog()
如果使用 Show(),窗口以非模态方式显示,脚本会继续执行。此时需要自行维持消息循环,通常只在交互式会话中临时使用。
关闭窗口后,可以读取返回值:
> $result = $form.ShowDialog()
> $result
#注意事项
- WinForms 只在 Windows 上可用,跨平台脚本应避免直接依赖它。
- WinForms 需要 STA 线程。若提示“调用线程必须为 STA”,请使用
pwsh -Sta启动。 - PowerShell 7 与 Windows PowerShell 5.1 都可以加载 WinForms,但 .NET 运行时版本不同,个别控件行为可能有差异。
- 复杂界面建议使用 C# 或专门的 UI 技术实现,PowerShell 更适合做简单的工具窗口。