2010. december 10., péntek

Change the border color of a TPanel


Problem/Question/Abstract:

Can I change black line color of the TPanel border (BorderStyle = bsSingle) into i.e. blue line color? I tried to trap the WM_NCPAINT message and to draw over the border line, but it's not working. The border line color is still black.

Answer:

That color is the COLOR_WINDOWFRAME, so you probably do not want to change it in general. But the NC paint handler should work. Here's some sample code to draw a border in red:

{ ... }
type
  TMyPanel = class(TPanel)
  protected
    procedure WM_NCPaint(var Msg: TWMNCPaint); message WM_NCPaint;
  end;

procedure TMyPanel.WM_NCPaint(var Msg: TWMNCPaint);
var
  DC: HDC;
  OldBrush: HBRUSH;
  OldPen: HPEN;
begin
  DC := 0;
  OldBrush := 0;
  OldPen := 0;
  try
    {Must use a WindowDC or you can't draw outside the client area}
    DC := GetWindowDC(Handle);
    {Use a "clear" brush and an appropriately colored pen}
    OldBrush := SelectObject(DC, GetStockObject(NULL_BRUSH));
    Canvas.Pen.Color := clRed;
    OldPen := SelectObject(DC, Canvas.Pen.Handle);
    {Draw the border}
    Rectangle(DC, 0, 0, Width, Height);
    {Tell Windows you did it}
    Msg.Result := 0;
  finally
    {Clean up the mess you made}
    if DC <> 0 then
    begin
      if OldPen <> 0 then
        SelectObject(DC, OldPen);
      if OldBrush <> 0 then
        SelectObject(DC, OldBrush);
      ReleaseDC(Handle, DC);
    end;
  end;
end;

{Dynamic panel creation}

{ ... }
Panel := TMyPanel.Create(Self);
with Panel do
begin
  Parent := Self;
  Left := 10;
  Top := 10;
  {Don't try to do 3D borders or add beveling - keep it simple}
  BevelOuter := bvNone;
  BorderStyle := bsSingle;
  Ctl3d := False;
end;
{ ... }

Nincsenek megjegyzések:

Megjegyzés küldése