PowerShell+WinForms:DropDownList样式ComboBox选中色修改异常
PowerShell WinForms ComboBox 自定义选中样式及Label抗锯齿修复
问题1:所有项背景均为Azure色的原因
你在DrawItem事件处理中未判断当前项的选中状态,导致所有项都应用了Azure背景色。需通过DrawItemEventArgs.State属性判断项是否处于选中状态,再分别设置背景色。
问题2:Label组件失去抗锯齿的原因
自定义绘制时若修改了Graphics对象的渲染模式,会影响整个窗体的文本渲染。需在绘制完成后恢复原始渲染设置,或在窗体初始化时全局设置抗锯齿。
修正后的代码示例
Add-Type -AssemblyName System.Windows.Forms Add-Type -AssemblyName System.Drawing $form = New-Object System.Windows.Forms.Form $form.Text = "ComboBox Test" $form.Size = New-Object System.Drawing.Size(300, 200) # 全局设置文本抗锯齿 $form.Add_Load({ [System.Windows.Forms.Application]::SetCompatibleTextRenderingDefault($false) $form.TextRenderingHint = [System.Drawing.Text.TextRenderingHint]::AntiAlias }) $comboBox = New-Object System.Windows.Forms.ComboBox $comboBox.Location = New-Object System.Drawing.Point(20, 20) $comboBox.Size = New-Object System.Drawing.Size(250, 20) $comboBox.DropDownStyle = [System.Windows.Forms.ComboBoxStyle]::DropDownList $comboBox.DrawMode = [System.Windows.Forms.DrawMode]::OwnerDrawFixed $comboBox.Items.AddRange(@("Item 1", "Item 2", "Item 3", "Item 4")) # 修正后的DrawItem事件处理 $comboBox.Add_DrawItem({ param($sender, $e) # 保存原始渲染模式 $originalRenderingHint = $e.Graphics.TextRenderingHint try { # 设置抗锯齿 $e.Graphics.TextRenderingHint = [System.Drawing.Text.TextRenderingHint]::AntiAlias # 清空当前项区域 $e.DrawBackground() # 判断选中状态,设置背景色 if ($e.State -band [System.Windows.Forms.DrawItemState]::Selected) { $e.Graphics.FillRectangle([System.Drawing.Brushes]::Azure, $e.Bounds) } else { $e.Graphics.FillRectangle([System.Drawing.Brushes]::White, $e.Bounds) } # 绘制文本 $text = $sender.Items[$e.Index].ToString() $e.Graphics.DrawString($text, $sender.Font, [System.Drawing.Brushes]::Black, $e.Bounds.X, $e.Bounds.Y) # 绘制焦点框(可选) $e.DrawFocusRectangle() } finally { # 恢复原始渲染模式 $e.Graphics.TextRenderingHint = $originalRenderingHint } }) $label = New-Object System.Windows.Forms.Label $label.Location = New-Object System.Drawing.Point(20, 60) $label.Size = New-Object System.Drawing.Size(250, 20) $label.Text = "测试抗锯齿文本" $form.Controls.Add($comboBox) $form.Controls.Add($label) $form.ShowDialog() | Out-Null
关键修复点说明
- 选中状态判断:使用
$e.State -band [System.Windows.Forms.DrawItemState]::Selected判断项是否被选中,仅为选中项设置Azure背景,未选中项用默认白色。 - 渲染模式恢复:在
try-finally块中保存并恢复Graphics对象的TextRenderingHint,避免影响其他控件的文本渲染。 - 全局抗锯齿设置:在窗体
Load事件中设置TextRenderingHint为AntiAlias,确保所有文本控件默认开启抗锯齿。
内容的提问来源于stack exchange,提问作者fmotion1
相关产品推荐
相关产品推荐

