更新时间:2016-01-23 17:10:54浏览次数:1+次
在新类中重载 DrawItem事件,自绘的按钮需要设置OwnerDraw风格,则会自动调用DrawItem函数。这是因为在MFC中,要想激活控件的自绘功能,要求该控件的属性中必须包含属性值BS_OMNERDRAW,这一步我们可以通过类向导为CXPButton类添加PreSubclassWindow()函数,在该函数中完成属性值的设置。当激活控件的自绘功能之后,每次控件状态改变的时候都会运行函数DrawItem(),该函数的作用就是绘制控件在各种状态下的外观。
typedef struct tagDRAWITEMSTRUCT {
UINT CtlType;
UINT CtlID;
UINT itemID;
UINT itemAction;
UINT itemState;
HWND hwndItem;
HDC hDC;
RECT rcItem;
DWORD itemData;
} DRAWITEMSTRUCT;
CtlType:指定参数类型。例:ODT_BUTTON、ODT_COMBOBOX、ODT_LISTBOX等。BOOL CWnd::SubclassWindow(HWND hWnd)
{
if (!Attach(hWnd))
return FALSE;
// allow any other subclassing to occur
PreSubclassWindow();
// now hook into the AFX WndProc
WNDPROC* lplpfn = GetSuperWndProcAddr();
WNDPROC oldWndProc = (WNDPROC)::SetWindowLongPtr(hWnd, GWLP_WNDPROC,
(INT_PTR)AfxGetAfxWndProc());
ASSERT(oldWndProc != AfxGetAfxWndProc());
if (*lplpfn == NULL)
*lplpfn = oldWndProc; // the first control of that type created
#ifdef _DEBUG
else if (*lplpfn != oldWndProc)
{
TRACE(traceAppMsg, 0, "Error: Trying to use SubclassWindow with incorrect CWnd\n");
TRACE(traceAppMsg, 0, "\tderived class.\n");
TRACE(traceAppMsg, 0, "\thWnd = $%08X (nIDC=$%08X) is not a %hs.\n", (UINT)(UINT_PTR)hWnd,
_AfxGetDlgCtrlID(hWnd), GetRuntimeClass()->m_lpszClassName);
ASSERT(FALSE);
// undo the subclassing if continuing after assert
::SetWindowLongPtr(hWnd, GWLP_WNDPROC, (INT_PTR)oldWndProc);
}
#endif
return TRUE;
}
在DrawItem中写代码:
void CMyButton::DrawItem(LPDRAWITEMSTRUCT lpDrawItemStruct)
{
// TODO: 添加您的代码以绘制指定项
//LPDRAWITEMSTRUCT lpDrawItemStruct;
CDC *pDC=CDC::FromHandle(lpDrawItemStruct->hDC);
UINT state=lpDrawItemStruct->itemState;
CRect rect=lpDrawItemStruct->rcItem;
CString str;
GetWindowText(str);
if(state & ODS_SELECTED)
{
pDC->DrawFrameControl(&rect,DFC_BUTTON,DFCS_BUTTONPUSH | DFCS_PUSHED);
}
else
{
pDC->DrawFrameControl(&rect,DFC_BUTTON,DFCS_BUTTONPUSH);
}
CSize Extent=pDC->GetTextExtent(str);
CPoint pt=CPoint(rect.CenterPoint().x-Extent.cx/2,rect.CenterPoint().y-Extent.cy/2);
//如果被选中
if (state & ODS_SELECTED)
{
//向一个点中添加x,y坐标
pt.Offset(1,1);
}
pDC->TextOut(pt.x,pt.y,str);
}
代码实现:
相关资讯