介绍函数:
void AFXAPI DDX_Control( CDataExchange* pDX, int nIDC, CWnd& rControl );
参数一:指向CDataExchange的指针,用于建立资料交换设备上下文;
参数二:控件IDC;
参数三:控件变量。
重写SetIcon()函数:
头文件:
void SetIcon(int nIconInId, int nIconOutId = NULL); //带参数的成员函数
源文件:
void CButtonST::SetIcon(int nIconInId, int nIconOutId)
{
HICON hIconIn; //定义HICON 变量,用于保存图片
HICON hIconOut;
HINSTANCE hInstResource = AfxFindResourceHandle(MAKEINTRESOURCE(nIconInId), RT_GROUP_ICON);
//鼠标点击时获得应用资源句柄
hIconIn = (HICON)::LoadImage(hInstResource/*AfxGetApp()->m_hInstance*/, MAKEINTRESOURCE(nIconInId), IMAGE_ICON, 0, 0, 0);
// 鼠标移开时加载图片
hIconOut = (nIconOutId == NULL) ? NULL : (HICON)::LoadImage(hInstResource/*AfxGetApp()->m_hInstance*/, MAKEINTRESOURCE(nIconOutId), IMAGE_ICON, 0, 0, 0);
SetIcon(hIconIn, hIconOut); //调用
}
void CButtonST::SetIcon(HICON hIconIn, HICON hIconOut)
{
// Note: the following two lines MUST be here! even if
// BoundChecker says they are unnecessary!
if (m_hIconIn != NULL) ::DestroyIcon(m_hIconIn); //判定是否与图片相关联
if (m_hIconOut != NULL) ::DestroyIcon(m_hIconOut);
// Set icon when the mouse is IN the button
m_hIconIn = hIconIn;
// Set icon when the mouse is OUT the button
m_hIconOut = (hIconOut == NULL) ? m_hIconIn : hIconOut;
ICONINFO ii; //ICONINFO 结构体
// Get icon dimension
ZeroMemory(&ii, sizeof(ICONINFO)); //ii内存设0
::GetIconInfo(m_hIconIn, &ii); //设置自定义图标
m_cxIcon = (BYTE)(ii.xHotspot * 2);
m_cyIcon = (BYTE)(ii.yHotspot * 2);
::DeleteObject(ii.hbmMask);
::DeleteObject(ii.hbmColor);
RedrawWindow();
} // End of SetIcon
程序流程:
a)添加头文件
CButton m_btn;定义一对象
b)在新建框架类中初始化
BOOL CMy5Dlg::OnInitDialog()
{
m_btn.SetIcon(IDI_ICON1,IDI_ICON2); //设置两幅图标
}
c)鼠标点击交换图片
void CMy5Dlg::DoDataExchange(CDataExchange* pDX)
{
DDX_Control(pDX,IDC_BUTTON1,m_btn);
}