CCheckSK - 扩展的复选框类






4.19/5 (10投票s)
2003年8月20日
2分钟阅读

153036

7483
本文讨论了 CCheckSK 类,该类扩展了 CButton MFC,可用于创建看起来像 LED 的复选框。
引言
此类派生自 MFC CButton
。它支持以下功能
- 显示 On/Off LED 以指示复选框的状态
- 显示图标以指示复选框的状态。可以使用资源 ID、文件名或
HICON
指定图标。 - 左/中/右对齐文本
- LED 左侧或右侧的文本
- 启用/禁用复选框
- 工具提示
本文演示了如何扩展 MFC 以子类化通用控件并应用所有者绘制以使其具有任何所需的外观。
使用代码
要使用该类,请按照以下步骤操作
- 将文件CCheckSK.h 和 CCheckSK.cpp 添加到您的项目。
- 在对话框上创建复选框。
- 打开类向导并为复选框创建控件变量。为“类别”选择“Control”,为“变量类型”选择“CButton”。
- 在对话框类的 .h 文件中包含 CCheckSK.h(在演示中,该文件是 checkDlg.h)
- 如果您已将复选框变量命名为
m_chk
,那么在对话框的头文件中,将有一行CButton m_chk;
将CButton
替换为CCheckSK
- 在对话框类的
OnInitDialog
的末尾,添加对CCheckSK
中相应方法的调用BOOL CCheckDlg::OnInitDialog() { ... m_chk1.SetCheck(TRUE); m_chk1.SetLedColor(RGB(255, 0, 0), RGB(128, 0, 0)); m_chk1.SetToolTip("Click on this to change the state"); m_chk5.SetIcon(IDI_ON, IDI_OFF); ... }
- 如果您想稍后更改复选框的外观,您可以从代码在运行时调用这些方法中的任何一个。
代码工作原理
我们首先从 CButton
MFC 派生 CCheckSk
类。
class CCheckSK : public CButton { .... }
为了使控件成为所有者绘制,需要将 BS_OWNERDRAW
样式添加到窗口样式中。为此,使用子类化。为此,PreSubclassWindow
方法被重写如下。
void CCheckSK::PreSubclassWindow() { UINT nBS = GetButtonStyle(); // the button should not be owner draw ASSERT((nBS & SS_TYPEMASK) != BS_OWNERDRAW); // This class supports only check boxes ASSERT(nBS & BS_CHECKBOX); // Switch to owner-draw ModifyStyle(SS_TYPEMASK, BS_OWNERDRAW, SWP_FRAMECHANGED); m_nStyle = GetWindowLong(GetSafeHwnd(), GWL_STYLE); CButton::PreSubclassWindow(); }
一旦设置了所有者绘制样式,框架将在每次需要重绘控件时调用 DrawItem
方法。因此必须实现此方法,并且必须将绘制 LED 或显示图标的所有代码添加到其中。此方法的实现有点长,以下代码段仅给出流程
void CCheckSK::DrawItem(LPDRAWITEMSTRUCT lpDIS) { // this class works only for push buttons ASSERT (lpDIS->CtlType == ODT_BUTTON); // get the device context pointer to draw into CDC* pDC = CDC::FromHandle(lpDIS->hDC); // get button state, selected? has focus? disabled? // draw bounding rectangle with color based on whether // the mouse is over the check box // if check box has focus then draw the focus rectangle // calculate LED's and text's rectangle // If icon is given then draw the icon // otherwise draw the LED using GDI functions // Calculate the rectangle for the text based on the // horizontal alignment style of the check box // if the button is disabled then draw etched text or draw plain text // Release all resources }
方法
CDialogSK
类中存在以下方法
DWORD SetIcon(int nIconOn, int nIconOff);
根据资源 ID 设置图标
DWORD SetIcon(HICON hIconOn, HICON hIconOff);
根据图标句柄设置图标
DWORD SetIcon(LPCTSTR lpszFileNameIn, LPCTSTR lpszFileNameOut);
根据图标文件的名称设置图标
BOOL SetLedColor(COLORREF colLedOn, COLORREF colLedOff);
如果未使用任何图标,则使用此方法设置 on/off LED 的颜色
BOOL SetLedSize (int nSize);
LED 的大小使用此方法更改。
void SetToolTip (LPCTSTR lpszText);
可以使用此方法更改复选框的工具提示
历史
- 这是初始版本。