How are GDI objects selected and destroyed by Sele

2019-03-02 08:20发布

问题:

As I am new to Visual C++, this might be a very basic question related to selecting a GDI object.

The following code snippet draws a light grey circle with no border.

cPen pen(PS_NULL, 0, (RGB(0,0,0)));
dc.SelectObject(& pen);
CBrush brush (RGB (192,192,192));
dc.SelectObject (&brush);
dc.Ellipse(0,0, 100,100);

All I understand from the code snippet is first an Object of Pen is created, and its a NULL Pen which would make the border disappear, the brush then creates a Circle of grey color, but how does dc use pen if it is already using brush? this is a bit confusing.

How does using dc.SelectObject() twice help? If the solid brush object is used to create a circle with grey color, how does creating pen object help, if it is anyway destroyed as brush object is created? how exactly does this thing work?

回答1:

SelectObject function is used to select five different types of objects into DC

  1. Pen
  2. Brush
  3. Font
  4. Bitmap and
  5. Region

The documentation states that The newly selected object replaces the previous object of the same type. So it means you can select pen and brush without any problem but you cant select pen twice.

And moreover to avoid resource leak you need to select the old pen/brush whatever you have selected earlier

CPen pen(PS_NULL, 0, (RGB(0,0,0)));
CPen *oldPen = dc.SelectObject(& pen);
CBrush brush (RGB (192,192,192));
CBrush *oldBrush = dc.SelectObject (&brush);
dc.Ellipse(0,0, 100,100);

dc.SelectObject(oldPen);
dc.SelectObject(oldBrush);


回答2:

DC object has current brush, current pen, current font etc. That is, current object of specific type. So you can select pen and brush simultaneously, but you cannot select two pens together. SelectObject internally sees the type of the handle.

Also, SelectObject returns you previous current object of the same type, which is unselected with selecting your handle you provided. You should save it and restore when you are finished.