How to color the background of a TComboBox with VCL styles enabled

混江龙づ霸主 提交于 2019-12-20 04:53:12

问题


I am trying to color the background of a TComboBox with VCL styles enabled like the way its described in this article but its not working.

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


回答1:


Depending of your Delphi version you must

Delphi XE2

For Delphi XE2 you must write a Style Hook

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

Simply remove the seClient value from the StyleElements propertty

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



来源:https://stackoverflow.com/questions/16538890/how-to-color-the-background-of-a-tcombobox-with-vcl-styles-enabled

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!