SetPixel
The SetPixel function sets the red, green, and blue (RGB) values of the pixel at the specified coordinates to the specified color.
BOOL SetPixel(
HDC hdc,
int x,
int y,
COLORREF crColor
);
HDC hdc,
int x,
int y,
COLORREF crColor
);
Parameters
| Parameter | Type | Description |
|---|---|---|
hdc |
HDC |
A handle to the device context. |
x |
int |
The x-coordinate of the pixel to be set. |
y |
int |
The y-coordinate of the pixel to be set. |
crColor |
COLORREF |
The red, green, and blue (RGB) color value of the pixel. This is a 32-bit value that specifies the intensity of red, green, and blue, respectively. You can specify a color by using the RGB macro. |
Return Value
If the function succeeds, the return value is a COLORREF value that represents the color of the pixel that was previously at the specified coordinates. If the function fails, the return value is CLR_INVALID.
Remarks
- This function returns the previous color of the pixel that was set. This allows you to restore the original pixel color if needed.
- The coordinates are always relative to the lower-left corner of the client area.
- For better performance, consider using SetPixelV if you do not need to retrieve the previous pixel color.
Note: Using
SetPixel excessively can be inefficient. For drawing multiple pixels or complex shapes, consider using memory device contexts and BitBlt for optimized graphics operations.
Example
The following code snippet demonstrates how to set a pixel at coordinates (100, 50) to red.
// Assume hdc is a valid device context handle
HDC hdc;
int x = 100;
int y = 50;
COLORREF redColor = RGB(255, 0, 0); // Red color
COLORREF previousColor = SetPixel(hdc, x, y, redColor);
if (previousColor == CLR_INVALID) {
// Handle error: Failed to set pixel
MessageBox(NULL, "Failed to set pixel!", "Error", MB_OK | MB_ICONERROR);
} else {
// Pixel successfully set. previousColor holds the original color.
// You could potentially restore it later if needed:
// SetPixel(hdc, x, y, previousColor);
}
Tip: The
COLORREF value is a 32-bit integer where the lower 24 bits specify the red, green, and blue components. The RGB macro simplifies creating this value: RGB(red, green, blue), where each component is an integer from 0 to 255.