MFC 自定义控件

MFC 自定义控件

需要在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)。

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=::GetSysColorBrush(COLOR_WINDOW);  
              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);   
}  

来自:http://6208051.blog.51cto.com/6198051/1058634

参考:http://blog.csdn.net/worldy/article/details/16337139