Should SelectObject be called for each object type after drawing with GDI?

loop123123 1 Reputation point
2020-09-12T02:02:37.467+00:00

In this MSDN code example, SelectObject(hdc,original) is called only once at the end of the paint code. I guess it replaces the original pen. But it appears that it doesn't replace the original brush. So is that unnecessary? I was under the impression that you had to restore each object type--i.e., pen, brush, etc. Do you only have to replace a single original object?

Windows API - Win32
Windows API - Win32
A core set of Windows application programming interfaces (APIs) for desktop and server applications. Previously known as Win32 API.
2,498 questions
{count} votes

2 answers

Sort by: Most helpful
  1. Castorix31 82,751 Reputation points
    2020-09-12T05:02:52.097+00:00

    You are right.
    And there is not even

    EndPaint(hWnd, &ps);
    

    in this code...

    0 comments No comments

  2. Rita Han - MSFT 2,161 Reputation points
    2020-09-14T09:25:18.39+00:00

    Hello @loop123123 ,

    It depends.

    Best practice is restoring the original object when you finished drawing with the new object because:

    The danger of leaving objects selected into a DC for an extended period of time is that the owner of the object won’t be able to destroy the object, because you can’t destroy objects while they are selected into a DC.

    However, you can leave them selected into your private DC if the objects you are selecting into the DC are all under your control, then you will know how to get them out if you need to.

    Refer to "What are the dire consequences of not selecting objects out of my DC?" for more detailed information.

    That document sample is not a complete and productive code. You can use it as getting started. For API usage please following the related API document: SelectObject function.

    Thank you!


    If the answer is helpful, please click "Accept Answer" and upvote it.

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    0 comments No comments