如何从 TListBox 中删除虚线焦点矩形?

How to remove the dotted focus rectangle from TListBox?

我正在使用 ListBox.Style := lbOwnerDrawFixedOnDrawItem:

procedure TForm1.ListBox1DrawItem(Control: TWinControl; Index: Integer;
  ARect: TRect; State: TOwnerDrawState);
begin
  with ListBox1.Canvas do begin
    Brush.Color := clWhite;
    Pen.Color := clWhite;
    FillRect(ARect);
  end;
end;

它应该给出一个空 space 来绘制我想要的任何东西,但它没有。当项目被聚焦时,我仍然可以看到它周围有一个虚线矩形。

如何去掉矩形?

焦点矩形由 VCL (*)TCustomListBox.CNDrawItem after OnDrawItem 事件中绘制处理程序 returns.

procedure TCustomListBox.CNDrawItem(var Message: TWMDrawItem); 

...

  ..
    if Integer(itemID) >= 0 then
      DrawItem(itemID, rcItem, State)      //-> calls message handler
    else
      FCanvas.FillRect(rcItem);
    if (odFocused in State) and not TStyleManager.IsCustomStyleActive then
      DrawFocusRect(hDC, rcItem);          //-> draws focus rectangle
  ..
..

无论您在事件处理程序中绘制什么,稍后都会被 VCL 聚焦


但请注意 VCL 使用 DrawFocusRect 绘制焦点矩形:

Because DrawFocusRect is an XOR function, calling it a second time with the same rectangle removes the rectangle from the screen.

所以你自己调用DrawFocusRect然后让VCL的调用擦除它:

procedure TForm1.ListBox1DrawItem(Control: TWinControl; Index: Integer;
  ARect: TRect; State: TOwnerDrawState);
begin
  with ListBox1.Canvas do begin
    Brush.Color := clWhite;
    Pen.Color := clWhite;
    FillRect(ARect);
    if odFocused in State then  // also check for styles if there's a possibility of using ..
      DrawFocusRect(ARect);
  end;
end;


(*) 通常默认 window 过程为所有者绘制的列表框项目绘制焦点矩形以响应 WM_DRAWITEM 消息。但是在 VCL 处理消息时,默认的 window 过程不会为列表框调用。