如何更改禁用的TComboBox的字体颜色?

4

我有一个TComboBoxStyle:= csOwnerDrawVariable;,我想要显示禁用的字体颜色为黑色而不是“灰色”。

这是使用此源代码得到的结果:

procedure TCustomComboBox.WndProc(var Message: TMessage);
begin
  case Message.Msg of
    CN_CTLCOLORMSGBOX .. CN_CTLCOLORSTATIC, //48434..48440
    WM_CTLCOLORMSGBOX .. WM_CTLCOLORSTATIC:
    begin
      Color:= GetBackgroundColor; // get's the current background state
      Brush.Color:= Color;
    end;
  end;
  inherited;
end;

enter image description here

我希望内部的Edit控件字体颜色为黑色。

如果我在WndProc或其他地方更改Font.Color:= clBlack,则没有任何反应。

谷歌搜索给了我一些有关将TEdit更改为只读的提示,但这并没有帮助我。

更新

在得到@Abelisto的提示后,现在这是我的简短解决方案。

TCustomComboBox = class (TComboBox)
protected
  procedure DrawItem(Index: Integer; Rect: TRect; State: TOwnerDrawState); override;
end;

procedure TCustomComboBox.DrawItem(Index: Integer; Rect: TRect; State: TOwnerDrawState);
begin
  if odComboBoxEdit in State then begin // If we are drawing item in the edit part of the Combo
    if not Enabled then
      Canvas.Font.Color:= clBlack; // Disabled font colors
    Canvas.Brush.Color:= GetBackgroundColor; // Get the right background color: normal, mandatory or disabled
  end;
  inherited DrawItem(Index, Rect, State);
end;

然后调用 SetTextColor,但请注意 inherited 调用会将其还原。 - TLama
@GuidoG 感谢你的提示,但是它不起作用。 - punker76
抱歉问一个愚蠢的问题,但是...你尝试使用OnDrawItem事件吗?或者重写DrawItem方法? - Abelisto
@Abelisto,OnDrawItem在使用csOwnerDrawVariable时无法正常工作,而在这种情况下我无法使用csOwnerDraw。 - punker76
奇怪。我刚刚检查了一下 Style := csOwnerDrawVariable;,并且 OnDrawItem 正常工作。不过我是在 D2007 上尝试的。 - Abelisto
显示剩余7条评论
1个回答

6

使用OnDrawItem事件。 在设计时没有特殊设置组件 - 所有操作都在代码中执行。只需将ComboBox1和Button1放在窗体上并分配相应的事件。

procedure TForm3.Button1Click(Sender: TObject);
begin
  ComboBox1.Enabled := not ComboBox1.Enabled; // Change Enabled state
end;

procedure TForm3.ComboBox1DrawItem(Control: TWinControl; Index: Integer;
  Rect: TRect; State: TOwnerDrawState);
var
  txt: string;
begin
  if Index > -1 then
    txt := ComboBox1.Items[Index]
  else
    txt := '';
  if odComboBoxEdit in State then // If we are drawing item in the edit part of the Combo
    if ComboBox1.Enabled then
    begin // Enabled colors
      ComboBox1.Canvas.Font.Color := clRed; // Foreground
      ComboBox1.Canvas.Brush.Color := clWindow; // Background
    end
    else
    begin // Disabled colors
      ComboBox1.Canvas.Font.Color := clYellow;
      ComboBox1.Canvas.Brush.Color := clGray;
    end;

  ComboBox1.Canvas.TextRect(Rect, Rect.Left, Rect.Top, txt); // Draw item. It may be more complex 
end;

procedure TForm3.FormCreate(Sender: TObject);
begin
  with ComboBox1 do // Setup combo props
  begin
    Items.Add('111');
    Items.Add('222');
    Items.Add('333');
    ItemIndex := 1;
    Style := csOwnerDrawVariable;
  end;
end;

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接