本文簡要講解在VS2010中怎樣實作自定義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)。
C++代碼
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=\'#\'" >
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);