Good questions. Let me give you an example program, which will answer all of your questions at the same time (maybe not in the order you like them to be answered, so please look at all of it before replying):
Originally posted by bennyandthejets
JasonD, if you delete the brush straight away, won't that mean you will lose the background brush before it's even used? When I was first trying brushes out, which was yesterday, I experimented on where to delete it. I found that you can only delete it after you never need to use it again, or else the background reverts to plain white. So how can you delete it straight away?
Also, why delete it twice?
The background brush is first set in WinMain() like so:
In WM_DESTROY, we destroy this brush like so:
wndclass.hbrBackground = CreateSolidBrush ( RGB(0,0,0) ) ;
// note that we do not save the handle to the brush.
// This is ok, since we can obtain it later.
This nifty code allows us to change the brush whenever we feel like it, since the WM_DESTROY message will always destroy the currently used brush for the background, which is the only brush ever avaiable at any given time (i.e. the others are destroyed as soon as they are not used):
(HBRUSH) SetClassLong (
(LONG) GetStockObject (WHITE_BRUSH)
// this code replaces the old brush with a stock brush
// (one that doesn't need to be deleted, which is normally
// what WinMain() sets the background brush to).
// NOTE: that SetClassLong() changes a 32-bit value in
// a window class structure, and we are using it to change
// the brush handle. SetClassLong() returns the value that
// we are replacing - the handle of the brush that is already
// there. DeleteObject() takes one parameter - the old
// brush's handle, and deletes it.
Therefore, we do not delete any brush twice, and we never delete a brush until it is no longer used.
(HBRUSH) SetClassLong (
(LONG) CreateSolidBrush (RGB (Rvalue,Gvalue,Bvalue))
// NOTE: that DeleteObject() deletes the brush already set
// as the background brush, as SetClassLong() returns this
// handle. SetClassLong replaces the old brush handle
// with the new brush handle that it makes with
// CreateSolidBrush() (that will be
// later deleted with this same function call OR the one
// in WM_DESTROY - either case, we needn't save the
// brush handle).
// Rvalue,Gvalue,Bvalue = 0..255, which is
// the 24-bit color of the new brush you want.
// RGB() is a macro, as I'm sure you know, that makes a
// COLORREF valye from these three bytes.