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

Tom*_*Tom 5 delphi listbox canvas ownerdrawn

我使用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;
Run Code Online (Sandbox Code Playgroud)

它应该给出一个空的空间来绘制我想要的东西,但事实并非如此.当项目聚焦时,我仍然可以看到它周围的虚线矩形.

如何删除矩形?

Ser*_*yuz 10

在事件处理程序返回,焦点矩形由VCL (*) in 绘制.TCustomListBox.CNDrawItem OnDrawItem

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
  ..
..
Run Code Online (Sandbox Code Playgroud)

无论你在事件处理程序中绘制什么,以后都会被VCL 集中.


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

因为DrawFocusRect是一个XOR函数,所以使用相同的矩形第二次调用它会从屏幕中删除矩形.

所以只要打电话给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;
Run Code Online (Sandbox Code Playgroud)


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