如何获取自定义样式颜色并应用到自定义标题栏(TTitleBar)
解决Delphi 11.1自定义标题栏(TTitleBar)样式适配问题
核心思路
要让自定义标题栏适配VCL样式,需通过Delphi内置的TStyleServices接口获取样式定义的颜色,并在样式切换、窗口状态变化时同步更新标题栏外观。
具体实现步骤
定位样式中的标题栏颜色元素
打开VCL Style Designer,找到对应样式里的标题栏相关颜色标识:- 激活窗口的标题栏背景:
scCaptionActive - 非激活窗口的标题栏背景:
scCaptionInactive - 标题栏文字颜色:
sfcCaptionText
- 激活窗口的标题栏背景:
编写颜色获取与更新逻辑
在自定义标题栏类中添加颜色更新方法,通过TStyleServices提取样式颜色:uses Vcl.Themes, Vcl.Styles.Utils; procedure TCustomTitleBar.RefreshStyleColors(const IsWindowActive: Boolean); var BgColor, TextColor: TColor; begin if not StyleServices.Enabled then begin // 未启用样式时使用系统默认值 Color := clCaption; Font.Color := clCaptionText; Exit; end; // 获取背景色 if IsWindowActive then StyleServices.GetStyleColor(scCaptionActive, BgColor) else StyleServices.GetStyleColor(scCaptionInactive, BgColor); Color := BgColor; // 获取文字颜色 StyleServices.GetStyleFontColor(sfcCaptionText, TextColor); Font.Color := TextColor; end;绑定状态变化事件
在主窗体中,给以下事件绑定刷新逻辑,确保状态变化时标题栏样式同步:procedure TMainForm.FormActivate(Sender: TObject); begin CustomTitleBar.RefreshStyleColors(True); end; procedure TMainForm.FormDeactivate(Sender: TObject); begin CustomTitleBar.RefreshStyleColors(False); end; procedure TMainForm.FormStyleChanged(Sender: TObject); begin CustomTitleBar.RefreshStyleColors(Active); end;控件显示适配
若标题栏内的菜单、下拉控件显示异常,需将自定义标题栏的ParentBackground属性设为False,避免继承父控件的样式背景;同时确保控件的StyleElements属性包含seFont,以便同步样式字体。
内容的提问来源于stack exchange,提问作者John Barrat
相关产品推荐
相关产品推荐

