SelectObject Function

The SelectObject function selects an object into the specified device context (DC).

GDI_OBJECT SelectObject( HDC hdc, GDI_OBJECT hgdiobj );

Parameters

Parameter Description
hdc A handle to the device context.
hgdiobj A handle to the object (a bitmap, brush, font, palette, or pen) to be selected into the DC.

Return Value

If the function succeeds, the return value is a handle to the object previously selected into the specified DC. If the function fails, the return value is NULL.

Remarks

A device context can have only one of each type of object selected at a time. For example, a DC can have only one bitmap, one brush, one font, one palette, and one pen selected at a time. When you select a new object of a type that is already selected into the DC, the previous object of that type is returned.

You should always save the handle to the previous object so that you can restore it to the DC later. This ensures that the DC is returned to its original state.

If you select a stock object (like those returned by GetStockObject) into a DC, you must not delete it using DeleteObject. Stock objects are managed internally by the system.

Note

It is important to call DeleteObject for objects you create (like those from CreateCompatibleBitmap or CreateSolidBrush) after you have finished using them. However, do not call DeleteObject for stock objects or objects created by other applications.

Warning

Attempting to delete a stock object or an object that is currently selected into a device context will lead to undefined behavior and potential application crashes.

Examples

The following code snippet demonstrates how to select a new font into a device context and restore the original font afterwards.


HDC hdc = GetDC(NULL); // Get a handle to the screen DC
if (hdc) {
    // Create a new font (example)
    HFONT hNewFont = CreateFont(...); // Replace with actual font creation parameters

    if (hNewFont) {
        // Select the new font into the DC, saving the old font
        HFONT hOldFont = (HFONT)SelectObject(hdc, hNewFont);

        // Use the new font for drawing operations...

        // Restore the original font
        if (hOldFont) {
            SelectObject(hdc, hOldFont);
        }

        // Delete the newly created font object (only if it was successfully created and not a stock object)
        DeleteObject(hNewFont);
    }

    ReleaseDC(NULL, hdc); // Release the DC
}
            

See Also