2

スタイルがシンプルに設定されたコンボボックスにビットマップを配置するにはどうすればよいですか? たとえば、Google Chrome では右側に星があり、Firefox では右側に矢印があります。私はこのコードを試しました:

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;

動作しますが、スタイル: csOwnerDrawFixed および csOwnerDrawVariable のみで、ビットマップは項目でのみ表示されます。

ありがとう。

4

1 に答える 1

7

...また、ビットマップはアイテムにのみ表示されます。

オーナー描画コンボ ボックスのエディターでビットマップを描画するにodComboBoxEditは、オーナー描画状態を確認します。

ここに画像の説明を入力

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;

所有者以外が描画したコンボ ボックスにビットマップを描画するには、カスタマイズされたWM_NCPAINTハンドラーを使用して、コンボ ボックス自体のウィンドウを描画する必要があります。

于 2013-01-11T21:33:39.690 に答える