如何在启用VCL样式的情况下为TComboBox的背景着色

时间:2013-05-14 08:55:15

标签: delphi vcl-styles

我试图为TComboBox的背景着色,启用VCL样式,就像它在本文中所描述的那样,但它不起作用。

http://theroadtodelphi.wordpress.com/2012/02/06/changing-the-color-of-edit-controls-with-vcl-styles-enabled/

1 个答案:

答案 0 :(得分:8)

根据您的Delphi版本,您必须

Delphi XE2

对于Delphi XE2,您必须编写样式挂钩

uses
  Vcl.Styles,
  Vcl.Themes;

type
  TComboBoxStyleHookExt= class(TComboBoxStyleHook)
    procedure UpdateColors;
  strict protected
    procedure WndProc(var Message: TMessage); override;
  public
    constructor Create(AControl: TWinControl); override;
  end;

  TWinControlClass= class(TWinControl);


{ TComboBoxStyleHookExt }

constructor TComboBoxStyleHookExt.Create(AControl: TWinControl);
begin
  inherited;
  UpdateColors;
end;

procedure TComboBoxStyleHookExt.UpdateColors;
const
  ColorStates: array[Boolean] of TStyleColor = (scComboBoxDisabled, scComboBox);
  FontColorStates: array[Boolean] of TStyleFont = (sfComboBoxItemDisabled, sfComboBoxItemNormal);
var
  LStyle: TCustomStyleServices;
begin
 if Control.Enabled then }//use the control colors
 begin
  Brush.Color := TWinControlClass(Control).Color;
  FontColor   := TWinControlClass(Control).Font.Color;
 end
 else
 begin //if not enabled. use the current style colors
  LStyle := StyleServices;
  Brush.Color := LStyle.GetStyleColor(ColorStates[Control.Enabled]);
  FontColor := LStyle.GetStyleFontColor(FontColorStates[Control.Enabled]);
 end;
end;

procedure TComboBoxStyleHookExt.WndProc(var Message: TMessage);
begin
  case Message.Msg of
    WM_CTLCOLORMSGBOX..WM_CTLCOLORSTATIC,
    CN_CTLCOLORMSGBOX..CN_CTLCOLORSTATIC:
      begin
        UpdateColors;
        SetTextColor(Message.WParam, ColorToRGB(FontColor));
        SetBkColor(Message.WParam, ColorToRGB(Brush.Color));
        Message.Result := LRESULT(Brush.Handle);
        Handled := True;
      end;
    CM_ENABLEDCHANGED:
      begin
        UpdateColors;
        Handled := False;
      end
  else
    inherited WndProc(Message);
  end;
end;

initialization
  TStyleManager.Engine.RegisterStyleHook(TComboBox, TComboBoxStyleHookExt);

Delphi XE3 / XE4

只需从 seClient 属性中删除 StyleElements

  ComboBox1.StyleElements:=[seFont, seBorder];
  ComboBox2.StyleElements:=[seFont, seBorder];
  ComboBox3.StyleElements:=[seFont, seBorder];

enter image description here