ComboBox Simple with Bitmap

懵懂的女人 提交于 2020-01-02 14:32:19

问题


How do I put a bitmap in a combobox with style set to simple? For example, Google Chrome has the star on the right, Firefox has the arrow on the right. I tried this code:

procedure TForm2.ComboBox1DrawItem(Control: TWinControl; Index: Integer;
Rect: TRect; State: TOwnerDrawState);
var
ComboBox: TComboBox;
bitmap: TBitmap;
begin
ComboBox := (Control as TComboBox);
Bitmap := TBitmap.Create;
try
ImageList1.GetBitmap(0, Bitmap);
with ComboBox.Canvas do
begin
  FillRect(Rect);
  if Bitmap.Handle <> 0 then Draw(Rect.Left + 2, Rect.Top, Bitmap);
  Rect := Bounds(Rect.Left + ComboBox.ItemHeight + 2, Rect.Top, Rect.Right - Rect.Left, Rect.Bottom - Rect.Top);
  DrawText(handle, PChar(ComboBox.Items[0]), length(ComboBox.Items[0]), Rect, DT_VCENTER+DT_SINGLELINE);
end;
finally
Bitmap.Free;
  end;
end;

works, but only with style: csOwnerDrawFixed and csOwnerDrawVariable, also the bitmaps are only visible on the items.

Thanks.


回答1:


... also the bitmaps are only visible on the items.

To draw your bitmap in the editor of an owner drawn combo box, check for odComboBoxEdit in the owner draw state:

type
  TComboBox = class(StdCtrls.TComboBox)
  private
    FBmp: TBitmap;
    FBmpPos: TPoint;
  protected
    procedure DrawItem(Index: Integer; Rect: TRect;
      State: TOwnerDrawState); override;
  public
    constructor Create(AOwner: TComponent); override;
    destructor Destroy; override;
  end;

constructor TComboBox.Create(AOwner: TComponent);
begin
  inherited Create(AOwner);
  FBmp := TBitmap.Create;
  FBmp.Canvas.Brush.Color := clGreen;
  FBmp.Width := 16;
  FBmp.Height := 16;
end;

destructor TComboBox.Destroy;
begin
  FBmp.Free;
  inherited Destroy;
end;

procedure TComboBox.DrawItem(Index: Integer; Rect: TRect;
  State: TOwnerDrawState);
begin
  TControlCanvas(Canvas).UpdateTextFlags;
  if Assigned(OnDrawItem) then
    OnDrawItem(Self, Index, Rect, State)
  else
  begin
    Canvas.FillRect(Rect);
    if Index >= 0 then
      Canvas.TextOut(Rect.Left + 2, Rect.Top, Items[Index]);
    if odComboBoxEdit in State then
    begin
      Dec(Rect.Right, FBmp.Width + Rect.Left);
      FBmpPos.X := Rect.Right + Rect.Left;
      FBmpPos.Y := (Height - FBmp.Height) div 2;
      if ItemIndex > -1 then
        Canvas.TextOut(Rect.Left + 2, Rect.Top, Items[ItemIndex]);
      Canvas.Draw(FBmpPos.X, FBmpPos.Y, FBmp);
    end;
  end;
end;

In order to draw a bitmap on non-owner drawn combo boxes, you will have to paint in the window of the combo box itself by using a customized WM_NCPAINT handler.



来源:https://stackoverflow.com/questions/14283783/combobox-simple-with-bitmap

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