Windows10下VB.NET如何获取标题栏颜色用于自定义无标题栏窗体
获取Windows 10标题栏颜色并应用到Panel
Windows 10的标题栏颜色属于系统主题着色色,需要调用DWM(桌面窗口管理器)API来获取,以下是具体实现方案:
1. 声明必要的Windows API函数
在窗体类顶部添加API声明,用于获取系统主题着色颜色:
Imports System.Runtime.InteropServices Public Class Form1 ' 调用DWM API获取系统着色颜色 <DllImport("dwmapi.dll", PreserveSig:=False)> Private Shared Sub DwmGetColorizationColor(ByRef colorizationColor As UInteger, ByRef opaqueBlend As Boolean) End Sub ' 用于监听系统主题变化的API <DllImport("user32.dll", SetLastError:=True, CharSet:=CharSet.Auto)> Private Shared Function RegisterWindowMessage(ByVal lpString As String) As UInteger End Function ' 主题颜色变化的消息常量 Private Const WM_DWMCOLORIZATIONCOLORCHANGED As UInteger = &H320 Private _wmSysColorChange As UInteger ' 其他代码... End Class
2. 编写获取标题栏颜色的方法
添加方法将API返回的数值转换为可直接使用的Color对象:
Private Function GetTitleBarColor() As Color Dim colorValue As UInteger Dim isOpaque As Boolean ' 调用API获取颜色值 DwmGetColorizationColor(colorValue, isOpaque) ' 提取RGB通道值(Windows 10标题栏默认不透明,alpha设为255) Dim red As Integer = CInt((colorValue And &HFF)) Dim green As Integer = CInt((colorValue And &HFF00) >> 8) Dim blue As Integer = CInt((colorValue And &HFF0000) >> 16) Return Color.FromArgb(255, red, green, blue) End Function
3. 在窗体加载时设置Panel颜色
修改你的Form1_Load事件,添加颜色赋值代码:
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load Me.Text = "" Me.ControlBox = False Me.FormBorderStyle = FormBorderStyle.Sizable ' 将标题栏颜色应用到upper_panel upper_panel.BackColor = GetTitleBarColor() End Sub
4. 监听主题变化自动更新颜色(可选)
如果需要在用户切换系统亮/暗色主题时自动同步颜色,添加消息监听逻辑:
Protected Overrides Sub OnHandleCreated(e As EventArgs) MyBase.OnHandleCreated(e) ' 注册系统颜色变化的监听消息 _wmSysColorChange = RegisterWindowMessage("WM_SYSCOLORCHANGE") End Sub Protected Overrides Sub WndProc(ByRef m As Message) MyBase.WndProc(m) ' 检测主题颜色变化消息,更新Panel颜色 If m.Msg = WM_DWMCOLORIZATIONCOLORCHANGED OrElse m.Msg = _wmSysColorChange Then upper_panel.BackColor = GetTitleBarColor() End If End Sub
注意事项
- 该方案仅适用于Windows平台,因为依赖Windows专属的DWM API
- 若使用.NET Core/.NET 5+,需确保项目引用
System.Runtime.InteropServices包
内容的提问来源于stack exchange,提问作者Visula Kavinda
相关产品推荐
相关产品推荐

