擷取物件屬性,選取新的物件
應用程式可以藉由呼叫 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堆積中的記憶體。