MFC 中自定義控件的創建與 Delphi/VB 不同,需手動註冊窗口類、編寫控件類、綁定對話框。本文記錄手動創建的完整步驟,避開類向導限制。
#ifndef __MYCONTROL_H__
#define __MYCONTROL_H__
#define MYWNDCLASS _T("mycontrol")
#include
class CMyControl : public CWnd
{
public:
static BOOL RegisterWndClass();
CMyControl();
void CustomFun(); // 自定義方法
};
#endif
#include "StdAfx.h"
#include "MyControl.h"
CMyControl::CMyControl() { RegisterWndClass(); }
BOOL CMyControl::RegisterWndClass()
{
WNDCLASS wc;
HINSTANCE hInst = AfxGetInstanceHandle();
// 若已註冊則直接返回
if (::GetClassInfo(hInst, MYWNDCLASS, &wc)) return TRUE;
wc.style = CS_DBLCLKS;
wc.lpfnWndProc = ::DefWindowProc;
wc.cbClsExtra = wc.cbWndExtra = 0;
wc.hInstance = hInst;
wc.hIcon = NULL;
wc.hCursor = AfxGetApp()->LoadStandardCursor(IDC_ARROW);
wc.hbrBackground = ::GetSysColorBrush(COLOR_WINDOW);
wc.lpszMenuName = NULL;
wc.lpszClassName = MYWNDCLASS;
if (!AfxRegisterClass(&wc))
{
AfxThrowResourceException();
return FALSE;
}
return TRUE;
}
void CMyControl::CustomFun()
{
AfxMessageBox(_T("My Custom Control!"));
}
IDC_CUSTOM1mycontrol(與 MYWNDCLASS 一致)class CCustomControlDlg : public CDialog
{
public:
CMyControl m_myControl; // 手動添加成員變量
// ...
};
void CCustomControlDlg::DoDataExchange(CDataExchange* pDX)
{
CDialog::DoDataExchange(pDX);
DDX_Control(pDX, IDC_CUSTOM1, m_myControl); // 手動綁定
}
void CCustomControlDlg::OnButtonTest()
{
m_myControl.CustomFun(); // 調用自定義方法
}
運行時控件不顯示? 必須在控件屬性的 Class 欄填入註冊的類名(mycontrol),否則 MFC 無法關聯窗口類,導致控件無法正常創建。
OnPaint 實現自繪IOleControl 等接口使其成為 ActiveX 控件手動創建 MFC 自定義控件的核心在於:註冊窗口類(RegisterWndClass)、繼承 CWnd、手動綁定 DDX_Control、設置資源屬性 Class 名稱。掌握此流程,即可構建功能豐富的可復用 UI 組件。