2024年4月28日发(作者:)

CButton::DrawItem

virtual void DrawItem( LPDRAWITEMSTRUCT lpDrawItemStruct );

Parameters

lpDrawItemStruct

A long pointer to a DRAWITEMSTRUCT structure. The structure contains information about the item

to be drawn and the type of drawing required.

Remarks

Called by the framework when a visual aspect of an owner-drawn button has changed. An owner-

drawn button has the BS_OWNERDRAW style set. Override this member function to implement drawing

for an owner-drawn CButton object. The application should restore all graphics device interface (GDI)

objects selected for the display context supplied in lpDrawItemStruct before the member function term

inates.

Also see the BS_ style values.

Example

// NOTE: CMyButton is a class derived from CButton. The CMyButton

// object was created as follows:

//

// CMyButton myButton;

// (_T("My button"),

// WS_CHILD|WS_VISIBLE|BS_PUSHBUTTON|BS_OWNERDRAW,

// CRect(10,10,100,30), pParentWnd, 1);

//

// This example implements the DrawItem method for a CButton-derived

// class that draws the button's text using the color red.

void CMyButton::DrawItem(LPDRAWITEMSTRUCT lpDrawItemStruct)

{

UINT uStyle = DFCS_BUTTONPUSH;

// This code only works with buttons.

ASSERT(lpDrawItemStruct->CtlType == ODT_BUTTON);

// If drawing selected, add the pushed style to DrawFrameControl.

if (lpDrawItemStruct->itemState & ODS_SELECTED)

uStyle |= DFCS_PUSHED;

// Draw the button frame.

::DrawFrameControl(lpDrawItemStruct->hDC, &lpDrawItemStruct->rcItem,

DFC_BUTTON, uStyle);

// Get the button's text.

CString strText;

GetWindowText(strText);

// Draw the button text using the text color red.

COLORREF crOldColor = ::SetTextColor(lpDrawItemStruct->hDC, RGB(255,0,0));

::DrawText(lpDrawItemStruct->hDC, strText, gth(),

&lpDrawItemStruct->rcItem, DT_SINGLELINE|DT_VCENTER|DT_CENTER);

::SetTextColor(lpDrawItemStruct->hDC, crOldColor);

}

在Windows中Edit,StaticBox的背景色都可以通过处理WM_CTLCOLOR消息来改变,但Push Button却不行。

唯一的方法是使用OwnerDraw风格的按钮。本文讲述的方法是使用CButton的派生类。

class CCButton : public CButton

{

DECLARE_DYNAMIC(CCButton)

public:

CCButton();

virtual ~CCButton();

BOOL CCButton::Attach(const UINT nID, CWnd* pParent)

protected:

virtual void DrawItem(LPDRAWITEMSTRUCT lpDIS);//必需重载的函数

public:

COLORREF m_fg, m_bg, m_disabled_fg, m_disabled_bg;//四种颜色分别为文字,背景,失效时文字,失效时背景

};

实现DrawItem

void CCButton::DrawItem(LPDRAWITEMSTRUCT lpDIS)

{

CDC* pDC = CDC::FromHandle(lpDIS->hDC);//???????DC

UINT state = lpDIS->itemState; //得到状态

CRect focusRect, btnRect;//两个矩形,表示得当输入焦点时的虚线矩形和按钮矩形

ct(&lpDIS->rcItem);