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

如何获取系统视觉样式渲染的WinForms ListBox/ListView的边框颜色

WinForms获取ListBox/ListView系统边框颜色解决方案

完全可以通过系统调用获取对应的系统边框颜色,分两种场景处理即可匹配系统原生渲染效果:

启用视觉样式(默认场景)

默认新建WinForms项目都会开启视觉样式,此时控件边框由系统主题定义,可通过Win32 API GetThemeColor 取值:

  • ListBox对应的主题类名为LISTBOX,边框部件取值为LP_BORDER
  • ListView对应的主题类名为LISTVIEW,边框部件取值为LVP_BORDER
  • 调用时传入对应类名、部件ID、TMT_COLOR 属性ID,即可拿到当前主题下的1px边框颜色值。

你可以通过.NET P/Invoke封装对该API的调用,示例封装代码如下:

[DllImport("uxtheme.dll", CharSet = CharSet.Unicode)]
private static extern int GetThemeColor(IntPtr hTheme, int iPartId, int iStateId, int iPropId, out int pColor);

[DllImport("uxtheme.dll", CharSet = CharSet.Unicode)]
private static extern IntPtr OpenThemeData(IntPtr hWnd, string pszClassList);

[DllImport("uxtheme.dll")]
private static extern int CloseThemeData(IntPtr hTheme);

// 调用示例:获取ListBox边框颜色
public Color GetListBoxBorderColor()
{
    IntPtr theme = OpenThemeData(IntPtr.Zero, "LISTBOX");
    if (theme != IntPtr.Zero)
    {
        int color;
        const int LP_BORDER = 2;
        const int TMT_COLOR = 3802;
        if (GetThemeColor(theme, LP_BORDER, 0, TMT_COLOR, out color) == 0)
        {
            CloseThemeData(theme);
            return ColorTranslator.FromWin32(color);
        }
        CloseThemeData(theme);
    }
    // 主题打开失败时降级用经典样式颜色
    return SystemColors.WindowFrame;
}

未启用视觉样式(经典模式场景)

如果系统关闭了主题渲染,或者程序手动禁用了视觉样式,此时所有控件边框统一使用系统经典配色,直接取SystemColors.WindowFrame即可,和原生ListBox/ListView边框完全一致。

注意事项

绘制时需要适配系统DPI缩放比例,不要直接写死1像素的边框宽度,避免高DPI场景下边框过细和原生控件效果不一致。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 01:45:01