I found some sample code like below, for trying to customize a scrollbar color:
HBRUSH CMainFrame::OnCtlColor(CDC* pDC, CWnd* pWnd, UINT nCtlColor)
{
HBRUSH hbr = CFrameWnd::OnCtlColor(pDC, pWnd, nCtlColor);
if(nCtlColor==CTLCOLOR_SCROLLBAR)
return m_brColor;
return hbr;
}
I found that the following code does not work:
procedure TForm1.WMCTLColor(var msg: TWMCTLCOLOR); message WM_CTLCOLOR;
How can I do it in Delphi?
There's no WM_CTLCOLOR
message in the native api. Instead you can use CN_CTLCOLORSCROLLBAR
control notification, which is send to child controls by the VCL in response to the API's WM_CTLCOLORSCROLLBAR
.
type
TScrollBar = class(TScrollBar)
protected
procedure WMCtlColor(var Message: TWMCtlColorScrollbar); message CN_CTLCOLORSCROLLBAR;
end;
procedure TScrollBar.WMCtlColor(var Message: TWMCtlColor);
begin
Message.Result := CreateSolidBrush(RGB(255, 255, 0));
end;
Or, if you don't want to derive a new control, provided the scrollbar is placed on the form:
TForm1 = class(TForm)
...
protected
procedure WMCtlColorScrollbar(var Message: TWMCtlColorScrollbar);
message WM_CTLCOLORSCROLLBAR;
...
end;
procedure TForm1.WMCtlColorScrollbar(var Message: TWMCtlColorScrollbar);
begin
if Message.ChildWnd = ScrollBar1.Handle then
Message.Result := CreateSolidBrush(RGB(255, 255, 0));
end;
This improvement avoids the memory leak by the repeated calling of CreateSolidBrush()
{ TMyScrollBar }
//******************************************************************************
constructor TMyScrollBar.Create(AOwner: TComponent);
begin
inherited;
FHBrush := CreateSolidBrush(ColorToRGB(FBackColor));
end;
//******************************************************************************
destructor TMyScrollBar.Destroy;
begin
DeleteObject(FHBrush);
inherited;
end;
//******************************************************************************
procedure TMyScrollBar.SetBackColor(const Value: Tcolor);
begin
FBackColor := Value;
DeleteObject(FHBrush);
FHBrush := CreateSolidBrush(ColorToRGB(FBackColor));
end;
//******************************************************************************
procedure TMyScrollBar.WMCtlColor(var Message: TWMCtlColorScrollbar);
begin
Message.Result := FHBrush;
end;