Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
858 views
in Technique[技术] by (71.8m points)

winapi - How are GDI objects selected and destroyed by SelectObject function

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...