PROGRAM TO HANDLE BASIC EVENTS
MESSAGE MAP,
SAVING THE VIEW’S STATE,
INITIALIZING A VIEW CLASS DATA MEMBERS.
SAVING THE VIEW’S STATE,
INITIALIZING A VIEW CLASS DATA MEMBERS.
Message map:
When the user presses the left mouse button in a view window, windows sends a message “WM_LBUTTONDOWN” to that window.
If the program needs to take an action in response to WM_LBUTTONDOWN, view class must have a member function that looks like:
Void CMyView::OnLButtonDown(UINT nFlags, CPoint point)
{
// event processing code here
}
Class header file must also have the prototype:
afx_msg void OnLButtonDown (UINT nFlags, CPoint point);
the afx_msg is a “no-op” that alerts that this is a prototype for a message map function.
Saving the View’s state:
The view’s OnDraw function draws an image based on the view’s current state and user actions can alter that state.
Two view class members used often are m_rectEllipse and m_nColor.
m_rectEllipse is an object of class CRect, which holds the current bounding rectangle of an ellipse.
m_nColor is an integer that holds the current ellipse color value.
By convention, MFC library nonstatic class data member names begin with m_.
Initializing a view class data member:
The most efficient place to initialize a class data member is in the constructor:
CMyView::CMyView:m_rectEllipse(0,0,200,200)
{
………..
}
Steps to create the application:
1. Run AppWizard to create second application.
2. Add the m_rectEllipse and m_nColor data members to secondView.
In the workspace window set to ClassView, right click the secondView class, select Add Member variable and then insert the data members:
private:
CRect m_rectEllipse;
int m_nColor;
3. Use ClassWizard to add a secondView class message handles.
Choose ClassWizard by right-click on the source window.
Select
Class Name: secondView
Object ID: SecondView
Messages: WM_LBUTTONDOWN (double-click)
the OnLButtonDown function name should appear in the Member functions list box.
4. Edit the OnLButtonDown code in secondView.cpp.
Click the edit code button in the ClassWizard and the code here:
void secondView::OnLButtonDown (UINT nFlags, CPoint point)
{
if (m_rectEllipse.PtInRect(point))
{
if (m_nColor == GRAY_BRUSH)
{
m_nColor = WHITE_BRUSH;
}
else
{
m_nColor = GRAY_BRUSH;
}
InvalidateRect (m_rectEllipse);
}
}
5. Edit the constructor and the OnDraw function in secondView class.
secondView :: secondView() : m_rectEllipse(0,0,200,200)
{
m_nColor = GRAY_BRUSH;
}
void secondView :: OnDraw (CDC* pDC)
{
pDC -> SelectStockObject (m_nColor);
pDC -> Ellipse (m_rectEllipse);
}
6. Build and run the program.
No comments:
Post a Comment