MFC-自定义控件

在对话框程序中使用。

ref.1

  1. 资源管理其中,拖拽自定义控件到对话框中
  2. 右键菜单创建 class,继承至 CWnd
  3. 比较重要的一步,需要注册自定义的控件,并且必须在构造函数里面注册
#define WNDCLASS_NAME (L"CCanvas")

BOOL CCanvas::RegisterWndClass()
{
WNDCLASS windowclass;
HINSTANCE hInst = AfxGetInstanceHandle();

//Check weather the class is registerd already
if (!(::GetClassInfo(hInst, WNDCLASS_NAME, &windowclass)))
{
//If not then we have to register the new class
windowclass.style = CS_DBLCLKS;// | CS_HREDRAW | CS_VREDRAW;
windowclass.lpfnWndProc = ::DefWindowProc;
windowclass.cbClsExtra = windowclass.cbWndExtra = 0;
windowclass.hInstance = hInst;
windowclass.hIcon = NULL;
windowclass.hCursor = AfxGetApp()->LoadStandardCursor(IDC_ARROW);
windowclass.hbrBackground = ::GetSysColorBrush(COLOR_WINDOW);
windowclass.lpszMenuName = NULL;
windowclass.lpszClassName = WNDCLASS_NAME;

if (!AfxRegisterClass(&windowclass))
{
AfxThrowResourceException();
return FALSE;
}
}

return TRUE;
}

CCanvas::CCanvas()
{
RegisterWndClass();
}
  1. 绑定类和自定义控件。右键单击-属性-class 里面填写类定义里面的 “CCanvas”
  2. 数据绑定,在对话框主程序中添加
CCanvas m_canvas;//This is our custom control

void CdrawDemoDlg::DoDataExchange(CDataExchange* pDX)
{
CDialogEx::DoDataExchange(pDX);
DDX_Control(pDX, IDC_STATIC_FRAME, m_ctrl_draw);
DDX_Control(pDX, IDOK, m_btn_ok);
DDX_Control(pDX, IDC_CUSTOM1, m_canvas);
}