天天看点

VS2010中如何实现自定义MFC控件

本文简要讲解在VS2010中怎样实现自定义MFC控件的知识,以下是分步骤说明。

       一、自定义一个空白控件

       1、先创建一个MFC工程

       NEW Project-->MFC-->MFC Application-->name:  “CustomCtr”-->Application Type选择“Dialog based”。

       2、在窗口中添加一个自定义控件

       Toolbox-->“Custom Control”-->属性-->class随便填写一个控件类名“CMyWin”, 这个名字用于以后注册控件用的,注册函数为RegisterWindowClass()。

       3、创建一个类

       在窗口中,右击custom control 控件-->ClassWizard-->ClassWizard-->Add Class-->类名CMyTest(以C开头)-->Base class:CWnd。

        4、注册自定义控件MyWin

       在MyTest类.h文件中声明注册函数BOOL   RegisterWindowClass(HINSTANCE hInstance = NULL)。

C++代码

BOOL CMyTest::RegisterWindowClass(HINSTANCE hInstance)   

{   

      LPCWSTR className = L"CMyWin";//"CMyWin"控件类的名字   

       WNDCLASS windowclass;         

       if(hInstance)   

              hInstance = AfxGetInstanceHandle();   

       if (!(::GetClassInfo(hInstance, className, &windowclass)))   

       {                

              windowclass.style = CS_DBLCLKS;   

              windowclass.lpfnWndProc = ::DefWindowProc;   

              windowclass.cbClsExtra = windowclass.cbWndExtra = 0;   

              windowclass.hInstance = hInstance;   

              windowclass.hIcon = NULL;   

              windowclass.hCursor = AfxGetApp()->LoadStandardCursor(IDC_ARROW);   

              windowclass.hbrBackground=\'#\'" >   

              windowclass.lpszMenuName = NULL;   

              windowclass.lpszClassName = className;   

              if (!AfxRegisterClass(&windowclass))   

              {   

                     AfxThrowResourceException();   

                     return FALSE;   

              }   

       }   

       return TRUE;   

}  

       5、在MyTest类的构造器中调用 RegisterWindowClass()。

CMyTest::CMyTest()   

       RegisterWindowClass();   

       6、控件与对话框数据交换

       在CustomCtrDlg.h中定义一个变量:

       CMyTest    m_draw;

       在对话框类的CustomCtrDlg.cpp的DoDataExchange函数中添加DDX_Control(pDX,IDC_CUSTOM1,m_draw)。

void CCustomCtrDlg::DoDataExchange(CDataExchange* pDX)   

       CDialogEx::DoDataExchange(pDX);   

       DDX_Control(pDX,IDC_CUSTOM1,m_draw);   

       以上是自定义一个空白控件。

       二、在控件上绘图

       1、在CMyTest类中添加一个绘图消息

       在VS2010最左侧Class View中右击CMyTest类-->ClassWizard-->Messages-->WM_PAINT-->双击,开发环境自动添加OnPaint()函数及消息队列。

       2、编写OnPaint()函数

       例如:画一条直线

void CMykk::OnPaint()   

       CPaintDC dc(this); // device context for painting   

       // TODO: Add your message handler code here   

       // Do not call CWnd::OnPaint() for painting messages   

       CRect rect;   

       this->GetClientRect(rect);   

       dc.MoveTo(0,0);   

       dc.LineTo(rect.right,rect.bottom);   

继续阅读