Today, we use MFC to create a small program for generating controls.
I checked some resources online and sorted them out here
First, generate the control (here the CButtonST is used as an example, and others are similar ):
// Generate button
Void CdlgDlg: OnBnClickedButton2 ()
...{
// TODO: add the control notification handler code here
Int width, height, left, space;
Width = height = 22;
Left = 100;
Space = 5;
Char cNum [10];
For (int I = 1; I <10; I ++)
...{
Itoa (I, cNum, 10 );
CButtonST * m_pBtnST = new CButtonST ();
M_pBtnST-> Create (cNum, WS_VISIBLE | WS_CHILD, CRect (CPoint (left, 100), CSize (width, height), this, IDC_SELECTBUTTON );
M_pBtnST-> ShowWindow (SW_SHOW );
This-> SelectButton (* m_pBtnST );
Left + = width + space;
}
}
Method 1:
# Define IDC_SELECTBUTTON 1011
// Add message processing
Afx_msg void OnBnClickedSelectButton ();
BEGIN_MESSAGE_MAP (CdlgDlg, CDialog)
ON_BN_CLICKED (IDC_SELECTBUTTON, & CdlgDlg: OnBnClickedSelectButton)
END_MESSAGE_MAP ()
// Add a message processing function
Void CdlgDlg: OnBnClickedSelectButton ()
...{
MessageBox ("clicked ");
}
Method 2 (this method is better. You can obtain the message triggered by the control ):
Add in. H file
Private:
Virtual BOOL OnCommand (WPARAM wParam, LPARAM lParam );
Add
BOOL CdlgDlg: OnCommand (WPARAM wParam, LPARAM lParam)
...{
If (LOWORD (wParam) = IDC_SELECTBUTTON & HIWORD (wParam) = BN_CLICKED) // select the button
...{
HWND hWnd = (HWND) lParam; // handle of the trigger message control
CButtonST * pST = (CButtonST *) CButtonST: FromHandle (hWnd); // Obtain the control pointer
If (this-> IsSelected (* pST ))
...{
This-> CancelSelectButton (* pST );
}
Else
...{
This-> SelectButton (* pST );
}
}
Return CDialog: OnCommand (wParam, lParam );
}
In this way, the message processing for dynamically adding controls is completed...
Method 3 (online collection, similar to Method 2, has not been tested ):
LRESULT CmmsgDlg: DefWindowProc (UINT message, WPARAM wParam, LPARAM lParam)
...{
Switch (message)
...{
Case WM_COMMAND:
...{
DWORD nID = LOWORD (wParam); // The ID of the low-key empty part.
DWORD nEv = HIWORD (wParam); // high-text form handle
Switch (nID)
...{
Case 0:
...{
Switch (nEv)
...{
Case BN_CLICKED: // BN_CLICKED secondary message
...{
AfxMessageBox ("Create Button is Cilcked .");
}
Break;
// Case BN_XXXX; other messages of this control
}
}
}
// Case other:
}
Break;
}
Return CDialog: DefWindowProc (message, wParam, lParam );
}
Haha... write this...