You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

.NET 6中Windows专属ListBox绘图代码的替代方案咨询

解决.NET 6中WinForms ListBox自定义绘制的警告问题

一、优化现有代码消除警告

你的代码出现警告主要是因为.NET 6中部分GDI+ API已过时,以及资源未正确释放,以下是针对性优化:

1. 修复PenAlignment.Inset过时警告

.NET Core/.NET 5+中PenAlignment.Inset已被标记为过时,可通过手动调整绘制矩形的坐标和尺寸来实现相同的内边框效果(笔宽2时,向内偏移1像素):

using (Pen penBorder = new Pen(Color.FromArgb(66, 66, 66), 2))
{
    // 手动调整矩形,替代PenAlignment.Inset的内缩效果
    var borderRect = new Rectangle(
        ModifiersLB.Location.X + 1,
        ModifiersLB.Location.Y + 1,
        ModifiersLB.Width - 2,
        ModifiersLB.Height - 2);
    graph.DrawRectangle(penBorder, borderRect);
}

2. 优化DrawItem事件代码

  • 正确释放SolidBrush(实现IDisposable接口,必须用using包裹)
  • 用TextRenderer.DrawText替代Graphics.DrawString,适配高DPI且文本渲染更清晰
  • 增加空值判断和焦点框绘制逻辑:
private void LB_DrawItem(object sender, DrawItemEventArgs e)
{
    ListBox lb = sender as ListBox;
    if (lb == null || e.Index < 0)
        return;

    Color bgColor = Color.FromArgb(50, 50, 50);
    Color selectedBgColor = Color.FromArgb(100, 100, 100);

    // 用using自动释放画刷资源
    using (SolidBrush bgBrush = new SolidBrush((e.State & DrawItemState.Selected) == DrawItemState.Selected ? selectedBgColor : bgColor))
    {
        e.Graphics.FillRectangle(bgBrush, e.Bounds);
    }

    string itemText = lb.Items[e.Index].ToString();
    // 使用TextRenderer绘制文本,适配高DPI
    TextRenderer.DrawText(
        e.Graphics,
        itemText,
        e.Font,
        e.Bounds,
        e.ForeColor,
        TextFormatFlags.Left | TextFormatFlags.VerticalCenter);

    // 绘制焦点框(可选,提升交互体验)
    if ((e.State & DrawItemState.Focus) == DrawItemState.Focus)
    {
        e.DrawFocusRectangle();
    }
}

3. 项目配置调整

确保你的项目目标框架设置为net6.0-windows(右键项目→属性→应用→目标框架),明确指定仅针对Windows平台,可消除跨平台相关的警告。

二、合适的替代控件

如果不想手动维护自定义绘制逻辑,可选择以下Windows平台原生控件:

  • ListView:设置View = View.List、HideSelection = false,通过OwnerDraw模式自定义绘制,功能比ListBox更丰富,.NET 6对其支持更完善,警告更少。
  • DataGridView:设置为单列布局,隐藏列头,可快速实现类似ListBox的效果,原生支持多种样式,无需大量自定义绘制代码。
  • 第三方控件:如DevExpress ListBoxControl、Telerik RadListBox,这些控件在.NET 6下有成熟支持,自带样式系统,无需手动绘制边框和项样式,但需引入第三方库。

内容的提问来源于stack exchange,提问作者Filipe

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.05 21:45:29