MFC的自定义控件步骤
MFC的自定义控件开发环境vs2015
步骤:新建一个MFC 工程在窗口中添加一个自定义控件
Toolbox-->“Custom Control”-->属性-->class随便填写一个控件类名“CMyControl”, 这个名字用于以后注册控件用的,注册函数为RegisterWindowClass()。
工具栏.png
创建自定义控件类
在Custom Control上右键点击 -->ClassWizard-->ClassWizard-->Add Class-->类名CMyControl(以C开头)-->Base class:CWnd。
类向导.png
创建控件类.png
注册自定义控件CMyControl代码语言:javascript复制 BOOL CMyControl::RegisterWindowClass(HINSTANCE hInstance)
{
LPCWSTR className = L"CMyControl";//"CMyControl"控件类的名字
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;
}
return AfxRegisterClass(&windowclass);
}在构造函数调用RegisterWindowClass()代码语言:javascript复制 CMyControl::CMyControl()
{
RegisterWindowClass();
} 在控件属性中填写当前自定控件的类名
注意控件的ID不能和其他的重复
控件属性.png
控件与对话框数据交换
在CMyTestDlg.h中定义一个变量:
CMyControl m_control;
在对话框类的CMyTestDlg.cpp的DoDataExchange函数中添加
DDX_Control(pDX,IDC_CUSTOM1,m_control)。代码语言:javascript复制 void CMyTestDlg::DoDataExchange(CDataExchange* pDX)
{
CDialogEx::DoDataExchange(pDX);
DDX_Control(pDX, IDC_CUSTOM1, m_control);
}以上步骤就完成了一个简单的自定控件