一、注冊Custom Control類
要使用Custom Control,必須把Custom Control的Class屬性設(shè)置為一個(gè)窗口類,這個(gè)窗口類可以VC的類,例如:Button、Edit。
在窗體上拉個(gè)Custom Control,設(shè)置ID為IDC_EDIT,Class為Edit。在頭文件增加一個(gè)CEdit類的成員變量:CEdit m_Text;
然后在OnInitDialog()中使用SubclassDlgItem把IDC_EDIT和對話框連接起來:
m_Text.SubclassDlgItem(IDC_EDIT,this);
m_Text.SetWindowText("Custom Control例子");
也可以把Custom Control設(shè)置為一個(gè)自定義類。
使用RegisterClass注冊自定義類,然后設(shè)置Custom Control的Class屬性為該類就行了,參考注冊自定義類的代碼:
BOOL CMyCtrl::RegisterWndClass(HINSTANCE hInstance)
{
WNDCLASS wc;
wc.lpszClassName = "CMyCtrl"; // 自定義類名
wc.hInstance = hInstance;
wc.lpfnWndProc = ::DefWindowProc;
wc.hCursor = ::LoadCursor(NULL, IDC_ARROW);
wc.hIcon = 0;
wc.lpszMenuName = NULL;
wc.hbrBackground = (HBRUSH) ::GetStockObject(LTGRAY_BRUSH);
wc.style = CS_GLOBALCLASS;
wc.cbClsExtra = 0;
wc.cbWndExtra = 0;
// 注冊自定義類
return (::RegisterClass(&wc) != 0);
}
二、映射自定義消息
這里只介紹Custom Control向父窗口發(fā)送WM_NOTIFY消息,然后映射到操作函數(shù)。
在自定義操作類里增加一個(gè)Login()成員函數(shù),當(dāng)主程序調(diào)用這個(gè)成員函數(shù)后,會(huì)觸發(fā)LoginEvent事件。
Login()的實(shí)現(xiàn)代碼:
BOOL CMyCtrl::Login()
{
AfxMessageBox("主程序調(diào)用Login,將觸發(fā)LoginEvent事件!");
NMHDR nm;
// 設(shè)置消息代碼
nm.code = 12345;
nm.hwndFrom =m_hWnd;
nm.idFrom = GetDlgCtrlID();
// 發(fā)父窗口發(fā)送WM_NOTIFY消息
CWnd* pParent = GetParent();
pParent->SendMessage(WM_NOTIFY,nm.idFrom, (LPARAM)&nm);
return true;
}
在主窗體的頭文件里聲明消息響應(yīng)函數(shù):
afx_msg void LoginEvent;
在BEGIN_MESSAGE_MAP里加上:
ON_NOTIFY(12345, IDC_CUSTOM1, LoginEvent)
12345:消息代碼;
IDC_CUSTOM1:控件的ID
LoginEvent:映射的函數(shù)。
然后再實(shí)現(xiàn)LoginEvent()的代碼:
void CMainDlg::LoginEvent()
{
AfxMessageBox("觸發(fā)LoginEvent事件!");
}
也可以在主窗體的OnNotify里處理WM_NOTIFY消息。