且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Powershell Windows窗体边框颜色/控件?

更新时间:2023-12-06 09:05:22

这可能很笨拙,但是您可以尝试在代码之上添加此辅助函数:

This may be cludgy, but you can try adding this helper function on top of the code:

function Paint-FocusBorder([System.Windows.Forms.Control]$control) {
    # get the parent control (usually the form itself)
    $parent = $control.Parent
    $parent.Refresh()
    if ($control.Focused) {
        $control.BackColor = "LightBlue"
        $pen = [System.Drawing.Pen]::new('Red', 2)
    }
    else {
        $control.BackColor = "White"
        $pen = [System.Drawing.Pen]::new($parent.BackColor, 2)
    }
    $rect = [System.Drawing.Rectangle]::new($control.Location, $control.Size)
    $rect.Inflate(1,1)
    $parent.CreateGraphics().DrawRectangle($pen, $rect)
}

并设置 GotFocus LostFocus 事件处理程序,如下所示:

and set up the GotFocus and LostFocus event handlers like this:

$txt_one.Add_GotFocus({ Paint-FocusBorder $this })
$txt_one.Add_LostFocus({ Paint-FocusBorder $this })
...
$txt_two.Add_GotFocus({ Paint-FocusBorder $this })
$txt_two.Add_LostFocus({ Paint-FocusBorder $this })

以及代码的结尾:

# call the Paint-FocusBorder when the form is first drawn
$form.Add_Shown({Paint-FocusBorder $txt_one})

# show the form
[void]$form.ShowDialog()

# clean-up
$form.Dispose()

P.S.在事件处理程序脚本块中,您可以使用 $ this

P.S. Inside an event handler scriptblock, you can refer to the control itself using the $this Automatic variable.

另外,在完成后执行 $ form.Dispose().