Re: Need Stock Object be selected out ?
On Nov 27, 5:12 am, "huang" <hzy...@hotmail.com> wrote:
After we call SelectObject to select in a GdiObject, we must call
SelectObject again to select out this GdiObject when we dont use it any
more.
My question is, after I call SelectStockObject or
SelectObject(GetStockObject(xxxx)), need I call SelectObject to select ou=
t
this stock object?
No, but you should better do it for the sake of good style. You can
say "well, this DC will go away before I do any operation that
concerns some brush other than the stock brush that I just put in".
But as you add more code, that assumption may become invalid (say, new
code needs your own brush, not the stock one you put in). On the other
hand, calling SelectObject "back" is easy and I bet you you will not
see it's cost.
In fact, good practice with SelectObject is to always use RAII:
class CTempSelection
{
public:
CTempSelection(CDC& dc, CGdiObject& o)
: m_dc(dc)
, m_pOriginal(&o.SelectObject(&o))
{}
~CTempSelection() { m_dc.SelectObject(m_pOriginal); }
private:
CDC& m_dc;
CGdiObject m_pOriginal;
};
then, in any painting, you do e.g.
// using b1 here
{
CTempSelection s(dc, b1);
PaintBabyPaint(dc);
} // b1 restored here.
Now, this doesn't work if you want to interleave selection of e.g. a
pen and a brush (select pen, paint some, select brush, paint some,
select another pen, paint more, select another brush). But to be
honest, if that happens often, your painting code is a mess.
Goran.