Visual C++ and MFC Fundamentals Chapter 18: Progress-Based Controls
Practical Learning: Using the OnTimer Event
- To generate the OnTimer() event, in the Class View tab, click the CRandShapesDlg
class. In the Properties window, click the Messages button
- Click the WM_TIMER field and click the arrow of its combo box. Select
OnTimer and implement the event as follows:
void CRandShapesDlg::OnTimer(UINT nIDEvent)
{
// TODO: Add your message handler code here and/or call default
CClientDC dc(this);
int x = (rand() % DlgWidth) + 10;
int y = (rand() % DlgHeight) + 10;
CBrush BrushRand(RGB(rand() % 255, rand() % 255, rand() % 255));
CPen PenRand(PS_SOLID, 1, RGB(rand() % 255,
rand() % 255, rand() % 255));
CBrush *pOldBrush = dc.SelectObject(&BrushRand);
CPen *pOldPen = dc.SelectObject(&PenRand);
switch(rand() % 5)
{
case 0:
dc.Ellipse(x, abs(y-200), abs(y-x), y);
break;
case 1:
dc.Rectangle(y, x, abs(y-x), (x+y)%255);
break;
case 2:
dc.RoundRect(y, x, y, x, abs(x-y), x+y);
break;
case 3:
dc.Ellipse(y, x, abs(x-y), x+y);
break;
case 4:
dc.Rectangle(x, y, abs(x-y), x+y);
break;
}
dc.SelectObject(pOldBrush);
dc.SelectObject(pOldPen);
CDialog::OnTimer(nIDEvent);
}
- To generate a random seed and to hide the cursor, in the OnInitDialog() event, call
ShorCursor(FALSE) and srand():
BOOL CRandShapesDlg::OnInitDialog()
{
CDialog::OnInitDialog();
// Set the icon for this dialog. The framework does this automatically
// when the application's main window is not a dialog
SetIcon(m_hIcon, TRUE); // Set big icon
SetIcon(m_hIcon, FALSE); // Set small icon
// TODO: Add extra initialization here