MFC自绘BUTTON 出错
我写了个CMyButton类,该类派生于CButton。我在网上看到说用SubclassDlgItem将派生类CMyButton的对象与对话框中的基类控件相连接,这样可以处理基类控件的消息。可是我这样做后,运行了对话框一闪就关闭了,求指导,我的代码如下:
CMyButton的头文件
#pragma once
#include "afxwin.h"
#ifndef _H_MYBUTTON_H
#define _H_MYBUTTON_H
class CMyButton :
public CButton
{
DECLARE_DYNAMIC(CMyButton)
public:
CMyButton(void);
~CMyButton(void);
void DrawItem(LPDRAWITEMSTRUCT lpDrawItemStruct);
void PreSubclassWindow();
protected:
//{{AFX_MSG(CMyButton)
afx_msg void OnMouseMove(UINT nFlags, CPoint point);
afx_msg void OnMouseHover(UINT nFlags, CPoint point);
afx_msg void OnMouseLeave();
//}}AFX_MSG(
DECLARE_MESSAGE_MAP()
public:
bool istrack_mousemove;
};
#endif
CMyButton的cpp文件
#include "MyButton.h"
IMPLEMENT_DYNAMIC(CMyButton,CButton)
CMyButton::CMyButton(void)
{
istrack_mousemove=true;
}
CMyButton::~CMyButton(void)
{
}
BEGIN_MESSAGE_MAP(CMyButton,CButton)
ON_WM_MOUSEMOVE()
ON_WM_MOUSEHOVER()
ON_WM_MOUSELEAVE()
ON_WM_DRAWITEM()
END_MESSAGE_MAP()
void CMyButton::OnMouseMove(UINT nFlags, CPoint point)
{
if (istrack_mousemove)
{
TRACKMOUSEEVENT mouseevent;
mouseevent.cbSize=sizeof(mouseevent);
mouseevent.dwFlags=TME_LEAVE|TME_HOVER;
mouseevent.dwHoverTime=10;
mouseevent.hwndTrack=this->GetSafeHwnd();
_TrackMouseEvent(&mouseevent);
istrack_mousemove=false;
}
//CButton::OnMouseMove( nFlags, point);
}
void CMyButton::OnMouseHover(UINT nFlags, CPoint point)
{
this->SetWindowText(_T("hover"));
//CButton::OnMouseHover( nFlags, point);
}
void CMyButton::OnMouseLeave()
{
istrack_mousemove=true;
this->SetWindowText(_T("leave"));
//CButton::OnMouseLeave();
}
void CMyButton::DrawItem(LPDRAWITEMSTRUCT lpDrawItemStruct)
{
//assert(lpDrawItemStruct->CtlType==ODT_BUTTON);
if (lpDrawItemStruct->itemState & ODS_FOCUS)
{
this->SetWindowText(_T("PUSH"));
}
}
void CMyButton::PreSubclassWindow()
{
ModifyStyle(0, BS_OWNERDRAW);//修改为自绘button
CButton::PreSubclassWindow();
}
然后我调用该CMyButton的对话框的OnInitDialog()里添加
p=new CMyButton; //p我在对话框的头文件里已定义为CMyButton *p
p->SubclassDlgItem(IDC_BN_1,this);
特别说明:
加了p->SubclassDlgItem(IDC_BN_1,this)后,运行时对话框就一闪而过
不加p->SubclassDlgItem(IDC_BN_1,this)这句,运行时对话框就可以显示
请问原因
[解决办法]
对话框里控件错误 , 引起对话框错误