检索对象属性,选择新对象
应用程序可以通过调用 GetCurrentObject 和 GetObject 函数来检索笔、画笔、调色板、字体或位图的属性。 GetCurrentObject 函数返回一个句柄,标识当前选定到 DC 中的对象;GetObject 函数返回一个结构,该结构描述对象的属性。
以下示例演示应用程序如何检索当前画笔属性,并使用检索到的数据来确定是否需要选择新的画笔。
HDC hdc; // display DC handle
HBRUSH hbrushNew, hbrushOld; // brush handles
HBRUSH hbrush; // brush handle
LOGBRUSH lb; // logical-brush structure
// Retrieve a handle identifying the current brush.
hbrush = GetCurrentObject(hdc, OBJ_BRUSH);
// Retrieve a LOGBRUSH structure that contains the
// current brush attributes.
GetObject(hbrush, sizeof(LOGBRUSH), &lb);
// If the current brush is not a solid-black brush,
// replace it with the solid-black stock brush.
if ((lb.lbStyle != BS_SOLID)
|| (lb.lbColor != 0x000000))
{
hbrushNew = GetStockObject(BLACK_BRUSH);
hbrushOld = SelectObject(hdc, hbrushNew);
}
// Perform painting operations with the solid-black brush.
// After completing the last painting operation with the new
// brush, the application should select the original brush back
// into the device context and delete the new brush.
// In this example, hbrushNew contains a handle to a stock object.
// It is not necessary (but it is not harmful) to call
// DeleteObject on a stock object. If hbrushNew contained a handle
// to a brush created by a function such as CreateBrushIndirect,
// it would be necessary to call DeleteObject.
SelectObject(hdc, hbrushOld);
DeleteObject(hbrushNew);
注意
应用程序在首次调用 SelectObject 函数时保存了原始画笔句柄。 保存此句柄,以便在使用新画笔完成最后一次绘制操作后,可以将原始画笔选回 DC。 将原始画笔选回 DC 后,将删除新画笔,从而释放 GDI 堆中的内存。