You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PowerShell 5.1中WinForms多行TextBox无法正常显示求助

问题原因及解决方法

你的TextBox无法正确显示多行文本,核心是两个问题导致的:

  1. TextBox高度设置不足
    你设置的$textBox.Size = New-Object System.Drawing.Size(260,20)中,高度仅为20像素,和单行TextBox的默认高度一致,即便开启了Multiline=$true,也没有足够空间展示多行内容。

  2. 文本读取方式丢失换行
    Get-Content默认返回字符串数组(每行是一个独立元素),直接赋值给TextBox.Text时,PowerShell会把数组元素用空格拼接,原本的换行符被丢弃,所有内容挤在一行显示。


修正后的完整代码

Add-Type -AssemblyName System.Windows.Forms
Add-Type -AssemblyName System.Drawing

# 使用-Raw参数读取完整文本,保留原始换行格式
$testText = Get-Content $PSScriptRoot\test.txt -Raw

$form = New-Object System.Windows.Forms.Form
$form.Text = 'Data Entry Form'
$form.Size = New-Object System.Drawing.Size(500,500)
$form.StartPosition = 'CenterScreen'

$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 = 'Display the text'
$form.Controls.Add($label)

$textBox = New-Object System.Windows.Forms.TextBox
$textBox.Location = New-Object System.Drawing.Point(10,130)
# 增大TextBox高度,给多行文本留出显示空间
$textBox.Size = New-Object System.Drawing.Size(260,200)
$textBox.Multiline = $true
$textBox.ReadOnly = $true
# 可选:添加垂直滚动条,方便查看长文本
$textBox.ScrollBars = [System.Windows.Forms.ScrollBars]::Vertical
$form.Controls.Add($textBox)

$okButton = New-Object System.Windows.Forms.Button
$okButton.Location = New-Object System.Drawing.Point(20,50)
$okButton.Size = New-Object System.Drawing.Size(75,23)
$okButton.Text = 'GO'
$okButton.Add_Click({
    $textBox.Text = $testText
})
$form.Controls.Add($okButton)

$form.Topmost = $true

$form.Add_Shown({$textBox.Select()})
$result = $form.ShowDialog()

关键修改说明

  • 读取文本添加-Raw参数:Get-Content -Raw会将整个文件内容作为单个字符串读取,保留原始换行符(\r\n),赋值给TextBox后能正确展示多行结构。
  • 调整TextBox高度:将Size的高度从20改为200(可根据需求调整),确保有足够空间显示多行内容。
  • 可选添加滚动条:当文本长度超过TextBox可视区域时,ScrollBars = Vertical允许用户滚动查看全部内容。

内容的提问来源于stack exchange,提问作者Ian Groen

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.03 10:52:43