How to show a borderless colored frame around a control like TPanel?
Just paint it - see code below.
For example, lets say there are two panels in a form and you click one of them. The clicked panel should show a frame around itself so the user can see which panel is selected.
Add a method which determines that one of these panels is the (grand...)parent of the focused control:
function TForm1.IsParentOfActiveControl(APanel: TPanel): Boolean;
var
C: TControl;
begin
C := ActiveControl.Parent;
while Assigned(C) do begin
if C = APanel then exit(true);
C := C.Parent;
end;
Result := false;
end;
In the OnPaint event of the panels check for the active control and set the border pen accordingly. Paint a rectangle around the panel outline with transparent brush:
procedure TForm1.Panel1Paint(Sender: TObject);
var
panel: TPanel;
begin
panel := Sender as TPanel;
panel.Canvas.Brush.Style := bsClear;
if IsParentOfActiveControl(panel) then begin
panel.Canvas.Pen.Color := clRed;
panel.Canvas.Pen.style := psSolid;
end else
panel.Canvas.Pen.Style := psClear;
panel.Canvas.Pen.Width := 3;
panel.Canvas.Rectangle(1, 1, panel.Width-1, panel.Height-1);
end;
Finally establish a handler for the OnEnter/OnExit events of the panels to force repainting when focus changes:
procedure TForm1.PanelEnter(Sender: TObject);
begin
(Sender as TPanel).Invalidate;
end;
procedure TForm1.PanelExit(Sender: TObject);
begin
(Sender as TPanel).Invalidate;
end;
Important note: While the new panel border may be clearly visible to you it may not be visible to all of your users because of theming. Suppose you draw the focused border in black, and the user has selected a black theme, black on black...