Changing background color
Hi all,
How do you programmatically change the background color of the view?
Thanks
# 1 Re: Changing background color
That could depend on what the view is. CView, CListView, etc. Non MFC view.
What kind of view are you looking at here ?
mdmd at 2007-11-11 1:04:30 >

# 3 Re: Changing background color
For example you can do it in OnDraw() function, creating a CBrush and a CPen with the desired color, selecting them in the DC and making a Rectangle filling all the client area.
# 4 Re: Changing background color
Here are couple other ways :
First in your PreCreateWindow function you can do something like this. Make sure
that you are able to delete the brush somewhere - this is just a sample.
BOOL CMyView::PreCreateWindow(CREATESTRUCT& cs)
{
// TODO: Modify the Window class or styles here by modifying
// the CREATESTRUCT cs
HBRUSH hBrush = CreateSolidBrush( RGB( 123, 123, 245 ) );
cs.lpszClass = AfxRegisterWndClass( 0, LoadCursor( NULL, IDC_ARROW ), hBrush, 0 );
return CView::PreCreateWindow(cs);
}
Or, override WM_ERASEBKGND and use code like the following. This isn't the only
code you could write, you could do just about anything you want to draw.
BOOL CMyView::OnEraseBkgnd(CDC* pDC)
{
CBrush br( GetSysColor( COLOR_ACTIVECAPTION ) );
CRect rect;
GetClientRect( & rect );
pDC->FillRect( & rect, & br );
return TRUE;
}
mdmd at 2007-11-11 1:07:31 >

# 5 Re: Changing background color
For the function: PrecreateWindow(...)
Why do I need to delete the brush? It is on the stack, so when the function is done the brush should be deleted, right?
Does the brush need to be deleted in the function: OnEraseBkgrd(...)
Thanks
# 6 Re: Changing background color
Not the way I wrote it. The HBRUSH will only be deleted by DeleteObject(). Its not
a CPP class object, its a simple Win32 data type.
I would suggest using a CBrush member variable and using that as the HBRUSH.
Then, when the window is destroyed the brush will be destroyed also via its
destructor. Don't create the CBrush locally, I don't think it'll work. I believe the
brush needs to have the same lifetime as the window. So its a bit different from
what we can do inside OnEraseBkgnd().
mdmd at 2007-11-11 1:09:34 >
