SelectObject
Function: SelectObject
Syntax:
HGDIOBJ SelectObject(HDC hdc, HGDIOBJ hgdiobj);
Parameters:
The SelectObject function selects an object into the specified device context (DC). A device context is a data structure that contains information about the drawing attributes of a physical or virtual device.
Description
This function returns the handle to the object that was previously selected into the specified device context. This handle can be used to restore the original object later.
The objects that can be selected into a device context include:
- Pens
- Brushes
- Fonts
- Bitmaps
- Palettes
- Regions
When you select an object into a device context, the previous object of the same type is returned. It is important to save this handle and restore the original object when you are finished with the new one to avoid resource leaks and unexpected behavior.
Parameters
| Parameter | Type | Description |
|---|---|---|
hdc |
HDC |
A handle to the device context. |
hgdiobj |
HGDIOBJ |
A handle to the object to be selected into the DC. This handle is obtained by calling a function such as CreatePen, CreateSolidBrush, CreateFont, CreateBitmap, or LoadBitmap. |
Return Value
| Type | Description |
|---|---|
HGDIOBJ |
If the function succeeds, the return value is a handle to the object that was previously selected into the specified device context. This handle can be used to restore the original object using SelectObject. If the function fails, the return value is NULL. |
Example Usage
The following code snippet demonstrates how to select a new brush into a device context and then restore the original brush:
// Assume hdc is a valid device context handle
HDC hdc = GetDC(NULL);
HGDIOBJ hOldBrush = NULL;
HBRUSH hNewBrush = CreateSolidBrush(RGB(255, 0, 0)); // Red brush
if (hNewBrush != NULL) {
// Select the new brush and save the old one
hOldBrush = SelectObject(hdc, hNewBrush);
// ... Perform drawing operations using the new red brush ...
// Restore the original brush
if (hOldBrush != NULL) {
SelectObject(hdc, hOldBrush);
}
// Delete the new brush
DeleteObject(hNewBrush);
}
// Release the device context
ReleaseDC(NULL, hdc);
Remarks
Always remember to restore the original object selected into the DC. Failure to do so can lead to resource leaks and corrupted graphics states.
The SelectObject function can be used to select various GDI objects, including pens, brushes, fonts, and bitmaps.