documentation 表示您尝试设置的那些属性是只读的。
您可以通过调用user32.dll SetSysColors 函数来做到这一点:
$signature = @'
[DllImport("user32.dll")]
public static extern bool SetSysColors(
int cElements,
int [] lpaElements,
uint [] lpaRgbValues);
'@
$type = Add-Type -MemberDefinition $signature `
-Name Win32Utils `
-Namespace SetSysColors `
-PassThru
$color = [Drawing.Color]::AliceBlue
# For RGB color values:
# $color = [Drawing.Color]::FromArgb(255,255,255)
$elements = @('13')
$colors = [Drawing.ColorTranslator]::ToWin32($color)
$type::SetSysColors($elements.Length, $elements, $colors)
其中13 元素表示COLOR_HIGHLIGHT,它是控件中所选项目的颜色。
运行上述代码后,结果如下:
组合框
文本框
您可以看到实际文本的颜色发生了变化,几乎看不到。要改变这一点,只需运行:
$color = [Drawing.Color]::Black
$elements = @('14')
$colors = [Drawing.ColorTranslator]::ToWin32($color)
$type::SetSysColors($elements.Length, $elements, $colors)
其中14 代表COLOR_HIGHLIGHTTEXT,它是控件中所选项目的文本颜色。
要了解有关SetSysColors 的更多信息,请查看PInvoke。此外,前往here 查找更多颜色代码。
我不知道是否可以仅使用WinForms 或SetSysColor 为PowerShell GUI 设置突出显示颜色,但您可以考虑的一种方法是使用WPF TextBox而不是WinForms。这样你就可以使用SelectionBrush和SelectionOpacity:
[xml]$xaml = @"
<Window
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
x:Name="Window"
Title="Initial Window"
WindowStartupLocation = "CenterScreen"
ResizeMode="NoResize"
SizeToContent = "WidthAndHeight"
ShowInTaskbar = "True"
Background = "lightgray">
<StackPanel >
<Label Content='Type in this textbox' />
<TextBox x:Name="InputBox"
Height = "50"
SelectionBrush= "Green"
SelectionOpacity = "0.5" />
</StackPanel>
</Window>
"@
$reader=(New-Object System.Xml.XmlNodeReader $xaml)
$Window=[Windows.Markup.XamlReader]::Load( $reader )
$Window.ShowDialog() | Out-Null