MFC 自定义控件

 

须要在MFC实现自定义控件功能,网上搜集找的以下方法实现:函数

如下是步骤说明。this

       1、自定义一个空白控件spa

       一、先建立一个MFC工程.net

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

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

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

       三、建立一个类开发

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

        四、注册自定义控件MyWinio

       在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; } 

 

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

CMyTest::CMyTest()   
{   
       RegisterWindowClass();   
}  
 

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

       在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);   
}  

 以上是自定义一个空白控件。
 
       2、在控件上绘图

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

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

       二、编写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

相关文章
相关标签/搜索