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

时间:2019-06-28 09:36:56

标签: winforms powershell listbox

我正在尝试将项目的高度设置为等于ListBox的高度。换句话说,在ListBox中只能看到一个项目。现在,有两个项目可见。

enter image description here

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()

我尝试将DrawModeIntegralHeight的属性都更改为无效。有什么建议吗?

1 个答案:

答案 0 :(得分:1)

如值名称所示,[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)