如何在 powershell 中更改 ListBox 中项目的高度?

How to change height of items in ListBox in powershell?

我试图将 items 的高度设置为等于 ListBox 的高度。换句话说,只有一个 item 必须在 ListBox 中可见。现在,有两个项目可见。

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

# $OwnerDrawVariable = [Windows.Forms.DrawMode]::OwnerDrawVariable
# $OwnerDrawFixed = [Windows.Forms.DrawMode]::OwnerDrawFixed

$form                            = New-Object Windows.Forms.Form
$form.ClientSize                 = '400,400'
$form.text                       = "Form"
$form.TopMost                    = $false

$listBox                = New-Object Windows.Forms.ListBox
$listBox.text           = "listBox"
$listBox.width          = 80
$listBox.height         = 30
$listBox.location       = New-Object Drawing.Point(70,10)
# $listBox.IntegralHeight = $false
# $listBox.DrawMode     = $OwnerDrawVariable
$listBox.ItemHeight     = 30

@('1','2','3') | ForEach-Object {[void] $listBox.Items.Add($_)}

$form.controls.AddRange(@($listBox))

[void]$form.ShowDialog()

我试过更改 DrawMode 属性 以及 IntegralHeight 都无济于事。有什么建议吗?

如值名称所示,[DrawMode]::OwnerDrawFixed 需要控件所有者(也就是您!)在屏幕上明确绘制项目。

您可以通过向 DrawItem 事件添加事件处理程序来实现 属性:

$listBox.add_DrawItem({
    param(
        [object]$sender,
        [System.Windows.Forms.DrawItemEventArgs]$eargs
    )

    $eargs.DrawBackground()

    $eargs.Graphics.DrawString($listBox.Items[$eargs.Index].ToString(), $eargs.Font, [System.Drawing.Brushes]::Black, $eargs.Bounds.Left, $eargs.Bounds.Top)
    $eargs.DrawFocusRectangle()
})

$eargs.Font是继承自$listbox.Font,所以如果你也想让绘制的字符串更大一点,那么修改一下:

$listBox.Font = [System.Drawing.Font]::new($listBox.Font.FontFamily.Name, 18)