Getting Input from the mouse
Windows uses a number of different messages-more than 20 in all-to report input events involving the mouse These messages fall into two rather broad categories:. Client-area mouse messages, which report events that occur in a window's client area, and nonclient -area Mouse Messages, Which Pertain To Events in A Window's Nonclient Area. AN "Event" can be any of the following:
The press or release of a mouse Button The Double Click of A Mouse Button The movement of the mouse
You'll typically ignore events in the nonclient area of your window and allow Windows to handle them. If your program processes mouse input, it's client-area mouse messages you'll probably be concerned with.
Client-Area Mouse Messages
Windows Reports Mouse Events in A Window's Client Area Using The Messages Shown in The Following Table.
Client-Area Mouse Messages
MessageSent WhenWM_LBUTTONDOWNThe left mouse button is pressed.WM_LBUTTONUPThe left mouse button is released.WM_LBUTTONDBLCLKThe left mouse button is double-clicked.WM_MBUTTONDOWNThe middle mouse button is pressed.WM_MBUTTONUPThe middle mouse button is released.WM_MBUTTONDBLCLKThe middle mouse button is double-clicked.WM_RBUTTONDOWNThe right mouse Button is presssed.wm_rbuttonupthe Right Mouse Button is released.wm_rbuttondblclkthe Right Mouse Button Is Double-Clicked.wm_mousemovethe Cursor is Moved over The Window's Client Area.
Messages that begin with WM_LBUTTON pertain to the left mouse button, WM_MBUTTON messages to the middle mouse button, and WM_RBUTTON messages to the right mouse button. An application will not receive WM_MBUTTON messages if the mouse has only two buttons. (This rule has one important exception:. mice that have mouse wheels Mouse wheels are discussed later in this chapter) An application will not receive WM_RBUTTON messages if the mouse has just one button The vast majority of PCs running Windows have two-button mice, so it's.. reasonably safe to assume that the right mouse button exists. However, if you'd like to be certain (or if you'd like to determine whether there is a third button, too), you can use the Windows :: GetSystemMetrics API function : int NButtonCount = :: getSystemMetrics;
The return value is the number of mouse buttons, or it is 0 in the unlikely Event this a mouse is not installed.
WM_xBUTTONDOWN and WM_xBUTTONUP messages report button presses and releases. A WM_LBUTTONDOWN message is normally followed by a WM_LBUTTONUP message, but do not count on that being the case. Mouse messages go to the window under the cursor (the Windows term for the mouse pointer) , so if the user clicks the left mouse button over a window's client area and then moves the cursor outside the window before releasing the button, the window receives a WM_LBUTTONDOWN message but not a WM_LBUTTONUP message. Many programs react only to button-down messages and ignore button-up messages, in which case the pairing of the two is not important. If pairing is essential, a program can "capture" the mouse on receipt of a button-down message and release it when a button-up message arrives . In between, all mouse messages, even those pertaining to events outside the window, are directed to the window that performed the capture. This ensures that a button-up message is received no matter where the cursor is when the button is released. Mouse capturing is discussed later in this chapter.When two clicks of the same button occur within a very short period of time, the second button-down message is replaced by a WM_xBUTTONDBLCLK message. Significantly, this happens only if the window's WNDCLASS includes the class style CS_DBLCLKS. The default WNDCLASS that MFC registers for frame windows has this style, so frame windows receive double-click messages by default. for a CS_DBLCLKS-style window, two rapid clicks of the left mouse button over the Window's Client Area Product The Following Sequence of Messages:
WM_LBUTTONDOWN
WM_LBUTTONUP
WM_LBUTTONDBLCLK
WM_LBUTTONUP
If the window is not registered to be notified of double copy, howare, the Same Two Button Click Singn
WM_LBUTTONUP
WM_LBUTTONDOWN
WM_LBUTTONUP
How your application responds to these messages-or whether it responds to them at all-is up to you. You should, however, steer away from having clicks and double clicks of the same mouse button carry out two unrelated tasks. A double-click message is always preceded by a single-click message, so the actions that generate the two messages are not easily divorced. Applications that process single and double clicks of the same button typically select an object on the first click and take some action upon that object On The Second Click. When You Double-Click A Folder in The Right Pane of The SECOND CLICK OPENS IT.
WM_MOUSEMOVE messages report that the cursor has moved within the window's client area. As the mouse is moved, the window under the cursor receives a flurry of WM_MOUSEMOVE messages reporting the latest cursor position. Windows has an interesting way of delivering WM_MOUSEMOVE messages that prevents slow applications from being overwhelmed by messages reporting every position in the cursor's path. Rather than stuff a WM_MOUSEMOVE message into the message queue each time the mouse is moved, Windows simply sets a flag in an internal data structure. The next time the application retrieves a message, Windows, seeing that the flag is set, manufactures a WM_MOUSEMOVE message with the current cursor coordinates. Therefore, an application receives WM_MOUSEMOVE messages only as often as it can handle them. If the cursor is moved very slowly, every point in its journey is reported Unless the application is busy doing other things. But if the cursor is whisked Very Rapidly Across The Screen, MOST applications receive only a handful of WM_MOUSEMOVE messages.In an MFC program, message-map entries route mouse messages to class member functions that are provided to handle those messages. The following table lists the message-map macros and message handler names for client-area Mouse Messages.
Message-map Macros and Message Handlers for Client-Area Mouse Messages
MessageMessage-Map MacroHandling FunctionWM_LBUTTONDOWNON_WM_LBUTTONDOWNOnLButtonDownWM_LBUTTONUPON_WM_LBUTTONUPOnLButtonUpWM_LBUTTONDBLCLKON_WM_LBUTTONDBLCLKOnLButtonDblClkWM_MBUTTONDOWNON_WM_MBUTTONDOWNOnMButtonDownWM_MBUTTONUPON_WM_MBUTTONUPOnMButtonUpWM_MBUTTONDBLCLKON_WM_MBUTTONDBLCLKOnMButtonDblClkWM_RBUTTONDOWNON_WM_RBUTTONDOWNOnRButtonDownWM_RBUTTONUPON_WM_RBUTTONUPOnRButtonUpWM_RBUTTONDBLCLKON_WM_RBUTTONDBLCLKOnRButtonDblClkWM_MOUSEMOVEON_WM_MOUSEMOVEOnMouseMoveOnLButtonDown and other client-area mouse message handlers are prototyped as follows:
AFX_MSG Void OnMSgname (uint nflags, cpoint point)
point identifies the location of the cursor. In WM_xBUTTONDOWN and WM_xBUTTONDBLCLK messages, point specifies the location of the cursor when the button was pressed. In WM_xBUTTONUP messages, point specifies the location of the cursor when the button was released. And in WM_MOUSEMOVE messages, point specifies the latest cursor position. in all cases, positions are reported in device coordinates relative to the upper left corner of the window's client area. A WM_LBUTTONDOWN message with point.x equal to 32 and point.y equal to 64 means the left mouse button Was Clicked 32 Pixels To The Right Of 64 Pixels Below The Client Area's Upper LEFT CORNER. IF Nessary, To Logical Coordinates Using MFC's CDC :: DPTOLP Function.
The nFlags parameter specifies the state of the mouse buttons and of the Shift and Ctrl keys at the time the message was generated. You can find out from this parameter whether a particular button or key is up or down by testing for the bit flags listed in The following table.
The nflags parameter
MaskMeaning If SetMK_LBUTTONThe left mouse button is pressed.MK_MBUTTONThe middle mouse button is pressed.MK_RBUTTONThe right mouse button is pressed.MK_CONTROLThe Ctrl key is pressed.MK_SHIFTThe Shift key is pressed.The expression
NFLAGS & MK_LBUTTON
Is Nonzero if and only if the left mouse button ispent, while
NFLAGS & MK_CONTROL
is nonzero if the Ctrl key was held down when the event occurred. Some programs respond differently to mouse events if the Shift or Ctrl key is held down. For example, a drawing program might constrain the user to drawing only horizontal or vertical lines if the Ctrl key is pressed as the mouse is moved by checking the MK_CONTROL bit in the nFlags parameter accompanying WM_MOUSEMOVE messages. At the conclusion of a drag-and-drop operation, the Windows shell interprets the MK_CONTROL bit to mean that the objects involved in the drop SHOULD be copied rather tour.
THE TICTAC APPLICATION
To show how easy it is to process mouse messages, let's look at a sample application that takes input from the mouse. TicTac, whose output is shown in Figure 3-1, is a tic-tac-toe program that responds to three types of client-area mouse events: left button clicks, right button clicks, and left button double clicks Clicking the left mouse button over an empty square places an X in that square Clicking the right mouse button places an O in an empty square (... The program prevents cheating by making sure that Xs and Os are alternated.) Double-clicking the left mouse button over the thick black lines that separate the squares clears the playing grid and starts a new game. After each X or O is placed, the program checks to see if there's a winner or the game has been played to a draw. A draw is declared when all nine squares are filled and neither player has managed to claim three squares in a row horizontally, vertically, or diagonally.Figure 3- The TICTAC WINDOW.
In addition to providing a hands-on demonstration of mouse-message processing, TicTac also introduces some handy new MFC functions such as CWnd :: MessageBox, which displays a message box window, and CRect :: PtInRect, which quickly tells you whether a point LIES INSIDE A Rectangle Reperesented by a CRect Object. Ticttac's Source Code APPEARS IN Figure 3-2.
Figure 3-2. The TICTAC Application.
Tictac.h # define EX 1
#define oh 2
Class CMYAPP: Public CWINAPP
{
PUBLIC:
Virtual Bool InitInstance ();
}
Class CmainWindow: Public CWnd
{
protected:
Static const crect m_rcsquares [9]; // Grid Coordinates
INT M_NGAMEGRID [9]; // Grid Contents
INT m_nnextchar; // Next Character (Ex Or OH)
INT getRectId (CPOINT POINT); Void Drawboard (CDC * PDC);
Void DrawX (CDC * PDC, INT NPOS);
Void Drawo (CDC * PDC, INT NPOS);
Void resetgame ();
Void CheckForgameOver ();
Int iswinner ();
Bool isdraw ();
PUBLIC:
CMAINWINDOW ();
protected:
Virtual void postncdestroy ();
AFX_MSG void onpaint ();
AFX_MSG Void ONLBUTTONDOWN (Uint Nflags, Cpoint Point);
AFX_MSG Void OnlbuttondblClk (uint nflags, cpoint point);
AFX_MSG Void OnRbuttondown (uint nflags, cpoint point);
Declare_message_map ()
}
Tictac.cpp #include
#include "ticttac.h"
CMYAPP myApp;
/
// CMYAPP Member Functions
Bool CmyApp :: InitInstance ()
{
m_pmainwnd = new cmainwindow;
m_pmainwnd-> showwindow (m_ncmdshow);
m_pmainwnd-> UpdateWindow ();
Return True;
}
/
// CMainWindow Message Map and Member Functions
Begin_MESSAGE_MAP (CMAINWINDOW, CWND)
ON_WM_PAINT ()
ON_WM_LBUTTONDOWN ()
ON_WM_LBUTTONDBLCLK ()
ON_WM_RBUTTONDOWN ()
END_MESSAGE_MAP ()
Const CRECT CMAINWINDOW :: M_RCSQUARES [9] = {
CRECT (16, 16, 112, 112),
CRECT (128, 16, 224, 112),
CRECT (240, 16, 336, 112),
CRECT (16, 128, 112, 224),
CRECT (128, 128, 224, 224),
CRECT (240, 128, 336, 224),
CRECT (16, 240, 112, 336),
CRECT (128, 240, 224, 336),
CRECT (240, 240, 336, 336)
}
CMAINWINDOW :: CMAINWINDOW ()
{
m_nnextchar = EX;
:: ZeromeMory (M_ngameGrid, 9 * Sizeof (int));
//
// register a wndclass.
//
CString strwndclass = afxregisterWndclass (
CS_DBLCLKS, // Class Style
AFXGetApp () -> LoadStandardCursor (IDC_ARROW), // Class Cursor
(Hbrush) (Color_3dface 1), // Background Brush
AfxGetApp () -> LoadStandardon (IDI_WINLOGO) // Class icon
);
//
// Create a window.//
Createex (0, strwndclass, _t ("tic-tac-toe"),
WS_OVERLAPPED | WS_SYSMENU | WS_CAPTION | WS_MINIMIZEBOX,
CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT,
NULL, NULL);
//
// size the window.
//
CRECT RECT (0, 0, 352, 352);
CalcwindowRect (& Re);
Setwindowpos (NULL, 0, 0, Rect.width (), Rect.height (),
SWP_NOZORDER | SWP_NOMOVE | SWP_NOREDRAW);
}
Void cmainwindow :: postncdestroy ()
{
DELETE THIS;
}
Void cmainwindow :: onpaint ()
{
CPAINTDC DC (this);
Drawboard (& DC);
}
Void CMainWindow :: ONLBUTTONDOWN (Uint Nflags, Cpoint Point)
{
//
// do Nothing if it's o's turn, if the click occurred outside the
// Tic-Tac-Toe Grid, or if a nonempty square.
//
IF (m_nnextchar! = EX)
Return;
INT NPOS = GetRectId (Point);
IF ((npos == -1) || (m_ngamegrid [npos]! = 0))
Return;
//
// add an x to the game Grid and Toggle M_NNEXTCHAR.
//
m_ngamegrid [npos] = ex;
m_nnextchar = oh;
//
// Draw an x on the screen and see if Either Player Has Won.
//
CClientDC DC (this);
Drawx (& DC, NPOS);
CheckForgameOver ();
}
Void CMainWindow :: OnRbuttondown (uint nflags, cpoint point)
{
//
// do Nothing if it's x's turn, if the click axcurred outside
// Tic-Tac-Toe Grid, or if a nonempty square.
//
IF (m_nnextchar! = oh)
Return;
INT NPOS = GetRectId (Point);
IF ((npos == -1) || (m_ngamegrid [npos]! = 0))
Return;
//
// add an o to the game grid and togle m_nnextchar.
//
m_ngamegrid [npos] = oh;
m_nnextchar = EX;
//
// Draw An O on The Screen and See IF Either Player Has Won.
//
CClientDC DC (this);
Drawo (& DC, NPOS);
CheckForgameOver ();
}
Void cmainwindow :: ONLBUTTONDBLCLK (uint nflags, cpoint point) {
//
// reset the game if one of the thick black Lines defining the game
// Grid Is Double-Clicked with The Left Mouse Button.
//
CClientDC DC (this);
IF (dc.getpixel (point) == RGB (0, 0, 0))
Resetgame ();
}
Int cmainwindow :: getRectId (cpoint point)
{
//
// Hit-test Each of the grid's nine squares and return a rectangle ID
// (0-8) IF (Point.x, Point.y) lies inside a square.
//
For (int i = 0; i <9; i ) {
IF (m_rcsquares [i] .ptinRect (Point))
Return I;
}
Return -1;
}
Void CMainWindow :: Drawboard (CDC * PDC)
{
//
// Draw the Lines That Define The TiC-Tac-Toe Grid.
//
CPEN PEN (PS_SOLID, 16, RGB (0, 0, 0));
CPEN * POLDPEN = PDC-> SELECTOBJECT (& PEN);
PDC-> Moveto (120, 16);
PDC-> LineTo (120, 336);
PDC-> MoveTo (232, 16);
PDC-> LineTo (232, 336);
PDC-> MoveTo (16, 120);
PDC-> LineTo (336, 120);
PDC-> Moveto (16, 232);
PDC-> LineTo (336, 232);
//
// Draw the xs and os.
//
For (int i = 0; i <9; i ) {
IF (m_ngamegrid [i] == ex)
Drawx (PDC, I);
Else IF (m_ngamegrid [i] == oh)
Drawo (PDC, I);
}
PDC-> SELECTOBJECT (POLDPEN);
}
Void CMainWindow :: DRAWX (CDC * PDC, INT NPOS)
{
CPEN PEN (PS_SOLID, 16, RGB (255, 0, 0));
CPEN * POLDPEN = PDC-> SELECTOBJECT (& PEN);
CRECT RECT = M_RCSQUARES [NPOS];
Rect.deflateRect (16, 16);
PDC-> MoveTo (Rect.Left, Rect.top);
PDC-> Lineto (Rect.right, Rect.Bottom);
PDC-> MoveTo (Rect.Left, Rect.Bottom);
PDC-> LINETO (Rect.right, Rect.top);
PDC-> SELECTOBJECT (POLDPEN);
}
Void CMainWindow :: Drawo (CDC * PDC, INT NPOS)
{
CPEN PEN (PS_SOLID, 16, RGB (0, 0, 255);
CPEN * POLDPEN = PDC-> SelectObject (& Pen); PDC-> SelectStockObject (null_brush);
CRECT RECT = M_RCSQUARES [NPOS];
Rect.deflateRect (16, 16);
PDC-> Ellipse (RECT);
PDC-> SELECTOBJECT (POLDPEN);
}
Void CMainWindow :: CheckForgameOver ()
{
Int nwinner;
//
// if The Grid Contains Three Consecutive XS or OS, Declare A Winner
// and start a new game.
//
IF (nwinner = iswinner ()) {
CString string = (nwinner == ex)?
_T ("x wins!"): _T ("o Wins!");
MessageBox (String, _T ("Game over"), MB_ICONEXCLAMATION | MB_OK;
Resetgame ();
}
//
// if The Grid Is Full, Declare A Draw and Start A New Game.
//
ELSE IF (isDraw ()) {
MessageBox (_T ("IT's A Draw!"), _T ("Game over"),
MB_ICONEXCLAMATION | MB_OK);
Resetgame ();
}
}
INT CMAINWINDOW :: Iswinner ()
{
Static int npattern [8] [3] = {
0, 1, 2,
3, 4, 5,
6, 7, 8,
0, 3, 6,
1, 4, 7,
2, 5, 8,
0, 4, 8,
2, 4, 6
}
For (int i = 0; i <8; i ) {
IF ((m_ngamegrid [npattern [i] [0] == EX) &&
(m_ngamegrid [npattern [i] [1] == ex) &&
(m_ngamegrid [npattern [i] [2] == ex))
Return EX;
IF ((m_ngamegrid [npattern [i] [0] == oh) &&
(m_ngamegrid [npattern [i] [1]] == oh) &&
(m_ngamegrid [npattern [i] [2]] == OH))
Return OH;
}
Return 0;
}
Bool cmainwindow :: isdraw ()
{
For (int i = 0; i <9; i ) {
IF (m_ngamegrid [i] == 0)
Return False;
}
Return True;
}
Void cmainwindow :: resetgame ()
{
m_nnextchar = EX;
:: ZeromeMory (M_ngameGrid, 9 * Sizeof (int));
Invalidate ();
}
The first step in processing mouse input is to add entries for the messages you want to handle to the message map CMainWindow's message map in TicTac.cpp contains the following message-map entries:. ON_WM_LBUTTONDOWN ()
ON_WM_LBUTTONDBLCLK ()
ON_WM_RBUTTONDOWN ()
These three statements correlate WM_LBUTTONDOWN, WM_LBUTTONDBLCLK, and WM_RBUTTONDOWN messages to the CMainWindow member functions OnLButtonDown, OnLButtonDblClk, and OnRButtonDown. When the messages start arriving, the fun begins.
The OnLButtonDown handler processes clicks of the left mouse button in CMainWindow's client area. After checking m_nNextChar to verify that it's X's turn and not O's (and returning without doing anything if it's not), OnLButtonDown calls the protected member function GetRectID to determine whether the click occurred in one of the nine rectangles corresponding to squares in the tic-tac-toe grid. The rectangles' coordinates are stored in the static array of CRect objects named CMainWindow :: m_rcSquares. GetRectID uses a for loop to determine whether the cursor location passed To it by the message handler lies inside any of the squares:
For (int i = 0; i <9; i ) {
IF (m_rcsquares [i] .ptinRect (Point))
Return I;
}
Return -1;
CRect :: PtInRect returns a nonzero value if the point passed to it lies within the rectangle represented by the CRect object, or 0 if it does not. If PtInRect returns nonzero for any of the rectangles in the m_rcSquares array, GetRectID returns the rectangle ID . The ID is an integer from 0 through 8, with 0 representing the square in the upper left corner of the grid, 1 the square to its right, 2 the square in the upper right corner, 3 the leftmost square in the second row, and so on. Each square has a corresponding element in the m_nGameGrid array, which initially holds all zeros representing empty squares. If none of the calls to PtInRect returns TRUE, GetRectID returns -1 to indicate that the click occurred outside the squares and OnLButtonDown ignores the mouse click. If, however, GetRectID returns a valid ID and the corresponding square is empty, OnLButtonDown records the X in the m_nGameGrid array and calls CMainWindow :: drawX to draw an X in the square. drawX creates a red pen 16 pixels wide and draws two perpendicular lines oriented at 45-degree angles.OnRButtonDown works in much the same way as OnLButtonDown, except that it draws an O instead of an X. The routine that does the drawing is CMainWindow :: DrawO. Before it draws An o with the cdc :: Ellipse Function, Drawo Selects a Null Brush INTO The Device Context:
PDC-> SelectStockObject (null_brush);
This prevents the interior of the O from being filled with the device context's default white brush. (As an alternative, we could have created a brush whose color matched the window's background color and selected it into the device context. But drawing with a NULL brush IS Slightly Faster Because It Products No Physical Screen Output.) THE O is TEN DRAWN with The StatementsCRect Rect = M_RCSQUARES [NPOS];
Rect.deflateRect (16, 16);
PDC-> Ellipse (RECT);
The first statement copies the rectangle representing the grid square to a local CRect object named rect; the second uses CRect :: DeflateRect to "deflate" the rectangle by 16 pixels in each direction and form the circle's bounding box; and the third draws the circle ............... ..
Double-clicking the grid lines separating the squares clears the Xs and Os and begins a new game. While this is admittedly a poor way to design a user interface, it does provide an excuse to write a double-click handler. (A better solution would be a push button control with the words New Game stamped on it or a New Game menu item, but since we have not covered menus and controls yet, the perfect user interface will just have to wait.) Left mouse button double clicks are Processed by cmainwindow :: ONLBUTTONDBLCLK, WHICH Contains these Simple Statements:
CClientDC DC (this);
IF (dc.getpixel (point) == RGB (0, 0, 0))
Resetgame ();
To determine whether the double click occurred over the thick black strokes separating the squares in the playing grid, OnLButtonDblClk calls CDC :: GetPixel to get the color of the pixel under the cursor and compares it to black (RGB (0, 0, 0) ). If there's a match, ResetGame is called to reset the game. Otherwise, OnLButtonDblClk returns and the double click is ignored. Testing the color of the pixel under the cursor is an effective technique for hit-testing irregularly shaped areas, but be wary Of Using Nonprimary Colors That A Display Driver is Likey to Dither. Pure Black (RGB (0, 0, 0)) and Pure White (RGB (255, 255, 255)) Aresu Supported On Every PC That Runs Windows, So you can safely assume that neither of these colors will be dithered.To be consistent with published user interface guidelines, applications should not use the right mouse button to carry out application-specific tasks as TicTac does. Instead, they should respond to right mouse clicks by popping Up context menus. by a WM_RBUTTONUP message is passed to the system for default processing, Windows places a WM_CONTEXTMENU message in the message queue. You'll learn more about this feature of the operating system in the next chapter.
Message Boxes
Before returning, TicTac's OnLButtonDown and OnRButtonDown handlers call CMainWindow :: CheckForGameOver to find out if the game has been won or played to a draw. If either player has managed to align three Xs or Os in a row or if no empty squares remain, CheckForGameOver calls CMainWindow's MessageBox function to display a message box announcing the outcome, as shown in Figure 3-3. MessageBox is a function that all window classes inherit from CWnd. It is an extraordinarily useful tool to have at your disposal because it provides a one- Step Means for Displaying a Message ON The Screen and OptionAl Obtaining A Response.figure 3-3. A Windows Message Box.
CWnd :: MessageBox Is Prototyped As Follows:
INT MessageBox (LPCTSTR LPSZTEXT, LPCTSTR LPSZCAPTION = NULL,
UINT NTYPE = MB_OK)
lpszText specifies the text in the body of the message box, lpszCaption specifies the caption for the message box's title bar, and nType contains one or more bit flags defining the message box's style. The return value identifies the button that was clicked to dismiss the message box. lpszText and lpszCaption can be CString objects or pointers to conventional text strings. (Because the CString class overloads the LPCTSTR operator, you can always pass a CString to a function that accepts an LPCTSTR data type.) A NULL lpszCaption value displays the caption "Error" in the title bar.
The Simplest Use for Messagebox Is To Display a Message and Pause Until The User Click The Message Box's Ok Button:
MessageBox (_T ("Click Ok To Continue"), _T ("My Application");
Accepting the default value for nType (MB_OK) means the message box will have an OK button but no other buttons. Consequently, the only possible return value is IDOK. But if you want to use a message box to ask the user whether to save a File Before Exiting The Application, You Can Use The MB_YESNOCANCEL STYLE: MessageBox (_T ("Your Document Contains unsaved Data. Save it?"),
_T ("My Application"), MB_YESNOCANCEL);
Now the message box contains three buttons-Yes, No, and Cancel-and the value returned from the MessageBox function is IDYES, IDNO, or IDCANCEL. The program can then test the return value and save the data before closing (IDYES), close without saving (IDNO), or return to the application without shutting down (IDCANCEL). The table below lists the six message box types and the corresponding return values, with the default push button-the one that's "clicked" if the user presses the Enter Key-highlighted in boldface type.
Message Box Types
TypeButtonsPossible Return CodesMB_ABORTRETRYIGNOREAbort, Retry, IgnoreIDABORT, IDRETRY, IDIGNOREMB_OKOKIDOKMB_OKCANCELOK, CancelIDOK, IDCANCELMB_RETRYCANCELRetry, CancelIDRETRY, IDCANCELMB_YESNOYes, NoIDYES, IDNOMB_YESNOCANCELYes, No, CancelIDYES, IDNO, IDCANCEL
In message boxes with multiple buttons, the first (leftmost) button is normally the default push button. You can make the second or third button the default by ORing MB_DEFBUTTON2 or MB_DEFBUTTON3 into the value that specifies the message box type. The statement
MessageBox (_T ("Your Document Contains unsaved Data. Save it?"),
_T ("My Application"), MB_YESNOCANCEL | MB_DEFBUTTON3);
Displays the Same Message Box as Before But Makes Cancel The Default Action.
By default, message boxes are application modal, which means the application that called the MessageBox function is disabled until the message box is dismissed. You can add MB_SYSTEMMODAL to the nType parameter and make the message box system modal. In 16-bit Windows, system -modal means that input to all applications is suspended until the message box is dismissed. In the Win32 environment, Windows makes the message box a topmost window that stays on top of other windows, but the user is still free to switch to other applications. System-modal message boxes should be used only for serious errors that demand immediate attention.You can add an artistic touch to your message boxes by using MB_ICON identifiers. MB_ICONINFORMATION displays a small text balloon with an "i" for "information" in it in The Upper Left Corner of The Message Box. The "i" is generally used when questions area being ask, AS in
MessageBox (_T ("No Errors found. Click Ok to Continue",
_T ("My Application", MB_ICONInformation | MB_OK);
MB_ICONQUESTION displays a question mark instead of an "i" and is normally used for queries such as "Save before closing?" MB_ICONSTOP displays a red circle with an X and usually indicates that an unrecoverable error has occurred-for example, an out-of -Memory Error Is Forcing The Program to Terminate Prematurely, Finally, MB_ICONEXCLAMATION Displays a Yellow Triangle Containing An Exclamation Mark. (See Figure 3-3.)
MFC provides an alternative to CWnd :: MessageBox in the form of the global AfxMessageBox function. The two are similar, but AfxMessageBox can be called from application classes, document classes, and other non-window classes. One situation in which AfxMessageBox is irreplaceable is when you want to report an error in the application object's InitInstance function. MessageBox requires a valid CWnd pointer and therefore can not be called until after a window is created. AfxMessageBox, on the other hand, can be called at any time.What? NO FRAME WINDOW?
TicTac differs from the sample programs in Chapters 1 and 2 in one important respect:. Rather than using a frame window for its main window, it derives its own window class from CWnd It's not that a CFrameWnd would not work; it's that CWnd has everything TicTac needs and more. CWnd is the root of all window classes in MFC. Depending on what kinds of applications you write, deriving from CWnd is something you might need to do often or not at all. Still, it's something every MFC programmer should Know how to do, and seeing a window class deact from cwnd also helps to understand, the point thing.
Creating your own CWnd-derived window class is simple. For starters, you derive the window class from CWnd instead of from CFrameWnd. In the BEGIN_MESSAGE_MAP macro, be sure to specify CWnd, not CFrameWnd, as the base class. Then, in the window's constructor, use AfxRegisterWndClass to register a WNDCLASS and call CWnd :: CreateEx to create the window. Remember the beginning of Chapter 1, where we looked at the C source code for an SDK-style Windows application? Before creating a window, WinMain initialized a WNDCLASS structure with values describing the window's class attributes and then called :: RegisterClass to register the WNDCLASS. Normally you do not register a WNDCLASS in an MFC program because MFC registers one for you. Specifying NULL in the first parameter to CFrameWnd :: Create accepts the default WNDCLASS. When you derive from CWnd, however, you must register your own WNDCLASS because CWnd :: CreateEx does not accept a NULL WNDCLASS name.The AfxRegisterWndClass Function
MFC makes WNDCLASS registration easy with its global AfxRegisterWndClass function. If you use :: RegisterClass or MFC's AfxRegisterClass to register a WNDCLASS, you must initialize every field in the WNDCLASS structure. But AfxRegisterWndClass fills in most of the fields for you, leaving you to specify Values for Just The Four That MFC Applications Are Typically Concerned with. AfxRegisterWndClass Is Prototyped As Follows:
LPCTSTR AFXREGISTERWNDCLASS (uint nclassstyle, hcursor hcursor = 0,
Hbrush hbrbackground = 0, Hicon Hicon = 0)
The value returned by AfxRegisterWndClass is a pointer to a null-terminated string containing the WNDCLASS name. Before seeing how TicTac uses AfxRegisterWndClass, let's take a closer look at the function itself and the parameters it accepts.nClassStyle specifies the class style, which defines certain ...........................
WNDCLASS style flags
Class StyleDescriptionCS_BYTEALIGNCLIENTEnsures that a window's client area is always aligned on a byte boundary in the video buffer to speed drawing operations.CS_BYTEALIGNWINDOWEnsures that the window itself is always aligned on a byte boundary in the video buffer to speed moving and resizing operations.CS_CLASSDCSpecifies that the window should share a device context with other windows created from the same WNDCLASS.CS_DBLCLKSSpecifies that the window should be notified of double clicks with WM_xBUTTONDBLCLK messages.CS_GLOBALCLASSRegisters the WNDCLASS globally so that all applications can use it. (By default, only the application that registers a WNDCLASS can create windows from it.) Used primarily for child window controls.CS_HREDRAWSpecifies that the entire client area should be invalidated when the window is resized horizontally.CS_NOCLOSEDisables the Close command on the system menu and the close button on the title bar.CS_OWNDCSpecifies that Each window created from this WNDC LASS should have its own device context. Helpful when optimizing repaint performance because an application does not have to reinitialize a private device context each time the device context is acquired.CS_PARENTDCSpecifies that a child window should inherit the device context of its parent.CS_SAVEBITSSpecifies that areas of the screen covered by windows created from this WNDCLASS should be saved in bitmap form for quick repainting. Used primarily for menus and other windows with short life spans.CS_VREDRAWSpecifies that the entire client area should be invalidated when the window is resized vertically.
The CS_BYTEALIGNCLIENT and CS_BYTEALIGNWINDOW styles were useful back in the days of dumb frame buffers and monochrome video systems, but they are largely obsolete today. CS_CLASSDC, CS_OWNDC, and CS_PARENTDC are used to implement special handling of device contexts. You'll probably use CS_GLOBALCLASS only if you write custom controls to complement list boxes, push buttons, and other built-in control types. The CS_HREDRAW and CS_VREDRAW styles are useful for creating resizeable windows whose content scales with the window size.hCursor identifies the "class cursor" for windows created from this WNDCLASS. When the cursor moves over a window's client area, Windows retrieves the class cursor's handle from the window's WNDCLASS and uses it to draw the cursor image. you can create custom cursors using an icon editor, or you can use the predefined system Cursors That Windows Provides. CWINAPP :: LoadStandardCursor Loads a System Cursor. The Statement
AFXGetApp () -> LoadStandardCursor (IDC_ARROW);
returns the handle of the arrow cursor that most Windows applications use. For a complete list of system cursors, see the documentation for CWinApp :: LoadStandardCursor or the :: LoadCursor API function. Generally speaking, only the IDC_ARROW, IDC_IBEAM, and IDC_CROSS cursors are Useful as class cursors.
The hbrBackground parameter passed to AfxRegisterWndClass defines the window's default background color. Specifically, hbrBackground identifies the GDI brush that is used to erase the window's interior each time a WM_ERASEBKGND message arrives. A window receives a WM_ERASEBKGND message when it calls :: BeginPaint in response to a WM_PAINT message. If you do not process WM_ERASEBKGND messages yourself, Windows processes them for you by retrieving the class background brush and using it to fill the window's client area. (you can create custom window backgrounds-for example, backgrounds formed from bitmap images-by processing WM_ERASEBKGND messages yourself and returning a nonzero value. The nonzero return prevents Windows from painting the background and overwriting what you wrote.) you can either provide a brush handle for hbrBackground or specify one of the predefined Windows system colors with the value 1 Added to IT, AS in Color_Window 1 or Color_AppWorkspace 1. See the documentation f or the :: GetSysColor API function for a complete list of system colors.The final AfxRegisterWndClass parameter, hIcon, specifies the handle of the icon that Windows uses to represent the application on the desktop, in the taskbar, and elsewhere. You can create a custom icon for your application and load it with CWinApp :: LoadIcon, or you can load a predefined system icon with CWinApp :: LoadStandardIcon. you can even load icons from other executable files using the :: ExtractIcon API function.
Here's What The Code to Register a Custom Wndclass Looks Like In Tictac.cpp:
CString strwndclass = afxregisterWndclass (
CS_DBLCLKS,
AfxGetApp () -> LoadStandardCursor (IDC_ARROW),
(Hbrush) (color_3dface 1),
AFXGetApp () -> LoadStandardicon (IDI_WINLOGO));
The class style CS_DBLCLKS registers the TicTac window to receive double-click messages. IDC_ARROW tells Windows to display the standard arrow when the cursor is over the TicTac window, and IDI_WINLOGO is one of the standard icons that Windows makes available to all applications. COLOR_3DFACE 1 assigns the TicTac window the same background color as push buttons, dialog boxes, and other 3D display elements. COLOR_3DFACE defaults to light gray, but you can change the color by using the system's Display Properties property sheet. Using COLOR_3DFACE for the background color gives .
AfxRegisterWndClass and Frame Windows
The AfxRegisterWndClass function is not only for applications that derive window classes from CWnd; you can also use it to register custom WNDCLASSes for frame windows The default WNDCLASS that MFC registers for frame windows has the following attributes:.
nClassStyle = CS_DBLCLKS | CS_HREDRAW | CS_VREDRAW hCursor = The handle of the predefined cursor IDC_ARROW hbrBackground = COLOR_WINDOW 1 hIcon = The handle of the icon whose resource ID is AFX_IDI_STD_FRAME or AFX_IDI_STD_MDIFRAME, or the system icon ID IDI_APPLICATION if no such resource is defined
Suppose you want to create a CFrameWnd frame window that lacks the CS_DBLCLKS style, that uses the IDI_WINLOGO icon, and that uses COLOR_APPWORKSPACE as its default background color Here's how to create a frame window that meets these qualifications.:
CString strwndclass = afxregisterWndclass (
CS_HREDRAW | CS_VREDRAW,
AfxGetApp () -> LoadStandardCursor (IDC_ARROW), (Hbrush) (Color_AppWorkspace 1),
AfxGetApp () -> LoadStandardon (IDI_WINLOGO)
);
Create (strwndclass, _t ("my frame window));
Thase Statements Replace the
Create (NULL, _T ("My Frame Window");
Statement That Normal Appears in a frame window's construction.
More about the TICTAC WINDOW
After registering a wndclass, Ticttac Creates Its Main Window with a call to cWnd :: Createex:
Createex (0, strwndclass, _t ("tic-tac-toe"),
WS_OVERLAPPED | WS_SYSMENU | WS_CAPTION | WS_MINIMIZEBOX,
CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT,
NULL, NULL);
The first parameter specifies the extended window style and is a combination of zero or more WS_EX flags. TicTac requires no extended window styles, so this parameter is 0. The second parameter is the WNDCLASS name returned by AfxRegisterWndClass, and the third is the window title . The fourth is the window style. The combination of WS_OVERLAPPED, WS_SYSMENU, WS_CAPTION, and WS_MINIMIZEBOX creates a window that resembles a WS_OVERLAPPEDWINDOW-style window but lacks a maximize button and can not be resized. What is it about the window that makes it NONRESIZEABLE? Look Up The definition of ws_overlappedwindow in Winuser.h (ONE OF SEVERAL LARGE Header Files That Comes with Visual C ), and you'll see Something Like this:
#define WS_OVERLAPPEDWINDOW (WS_OVERLAPPED | WS_CAPTION | WS_SYSMENU | WS_THICKFRAME | WS_MINIMIZE | WS_MAXIMIZE)
The WS_THICKFRAME STYLES AND CORNERS CAN Be Grabbed and Dragged With The Mouse. TiCtac's WINDOW Lacks this style, so the user can't resize it.
The next four parameters passed to CWnd :: CreateEx specify the window's initial position and size TicTac uses CW_USEDEFAULT for all four so that Windows will pick the initial position and size Yet clearly the TicTac window is not arbitrarily sized;.. It is sized to match The Playing Grid. But how? The Statements Following The Call To createex Hold The answer: CRECT Rect (0, 0, 352, 352);
CalcwindowRect (& Re);
Setwindowpos (NULL, 0, 0, Rect.width (), Rect.height (),
SWP_NOZORDER | SWP_NOMOVE | SWP_NOREDRAW);
The first of these statements creates a CRect object that holds the desired size of the window's client area-352 by 352 pixels. It would not do to pass these values directly to CreateEx because CreateEx's sizing parameters specify the size of the entire window, not just its client area. Since the sizes of the various elements in the window's nonclient area (for example, the height of the title bar) vary with different video drivers and display resolutions, we must calculate the size of the window rectangle from the client rectangle And the size the window to fit.
MFC's CWnd :: CalcWindowRect is the perfect tool for the job Given a pointer to a CRect object containing the coordinates of a window's client area, CalcWindowRect calculates the corresponding window rectangle The width and height of that rectangle can then be passed to CWnd..: : Setwindowpos to Effect The Proper Window Size. The Only Catch Is That CalcwindowRect Must Be Called After The Window Is Created So That It Can Factor in The Dimensions of The Window's Nonclient Area.
The Postncdestroy Function
Something you must consider when you derive your own window class from CWnd is that once created, the window object must somehow be deleted. As described in Chapter 2, the last message a window receives before it is destroyed is WM_NCDESTROY. MFC's CWnd class includes a . default OnNcDestroy handler that performs some routine cleanup chores and then, as its very last act, calls a virtual function named PostNcDestroy CFrameWnd objects delete themselves when the windows they are attached to are destroyed; they do this by overriding PostNcDestroy and executing a delete this . statement CWnd :: PostNcDestroy does not perform a delete this, so a class derived from CWnd should provide its own version of PostNcDestroy that does TicTac includes a trivial PostNcDestroy function that destroys the CMainWindow object just before the program terminates:. void CMainWindow :: Postncdestroy ()
{
DELETE THIS;
}
The question of "who deletes it" is something you should think about whenever you derive a window class from CWnd. One alternative to overriding CWnd :: PostNcDestroy is to override CWinApp :: ExitInstance and call delete on the pointer stored in m_pMainWnd.
Nonclient-area mouse messages
When the mouse is copy................. ..
Nonclient-area mouse messages
MessageSent WhenWM_NCLBUTTONDOWNThe left mouse button is pressed.WM_NCLBUTTONUPThe left mouse button is released.WM_NCLBUTTONDBLCLKThe left mouse button is double-clicked.WM_NCMBUTTONDOWNThe middle mouse button is pressed.WM_NCMBUTTONUPThe middle mouse button is released.WM_NCMBUTTONDBLCLKThe middle mouse button is double-clicked.WM_NCRBUTTONDOWNThe right mouse button is pressed.WM_NCRBUTTONUPThe right mouse button is released.WM_NCRBUTTONDBLCLKThe right mouse button is double-clicked.WM_NCMOUSEMOVEThe cursor is moved over the window's nonclient area.Notice the parallelism between the client-area mouse messages shown in the table below and the nonclient-area mouse messages; the only difference is the letters NC in the message ID Unlike double-click messages in a window's client area, WM_NCxBUTTONDBLCLK messages are transmitted regardless of whether the window was registered with the CS_DBLCLKS style..
As with client-area mouse messages, message-map entries route messages to the appropriate class member functions. The following table lists the message-map macros and message handlers for nonclient-area mouse messages.
Message-map macros and message handlers for nonclient-area mouse messages
MessageMessage-Map MacroHandling FunctionWM_NCLBUTTONDOWNON_WM_NCLBUTTONDOWNOnNcLButtonDownWM_NCLBUTTONUPON_WM_NCLBUTTONUPOnNcLButtonUpWM_NCLBUTTONDBLCLKON_WM_NCLBUTTONDBLCLKOnNcLButtonDblClkWM_NCMBUTTONDOWNON_WM_NCMBUTTONDOWNOnNcMButtonDownWM_NCMBUTTONUPON_WM_NCMBUTTONUPOnNcMButtonUpWM_NCMBUTTONDBLCLKON_WM_NCMBUTTONDBLCLKOnNcMButtonDblClkWM_NCRBUTTONDOWNON_WM_NCRBUTTONDOWNOnNcRButtonDownWM_NCRBUTTONUPON_WM_NCRBUTTONUPOnNcRButtonUpWM_NCRBUTTONDBLCLKON_WM_NCRBUTTONDBLCLKOnNcRButtonDblClkWM_NCMOUSEMOVEON_WM_NCMOUSEMOVEOnNcMouseMoveMessage handlers for nonclient-area mouse messages are prototyped this way:
AFX_MSG Void OnMSgname (uint nhittest, cpoint point)
Once again, the point parameter specifies the location in the window at which the event occurred. But for nonclient-area mouse messages, point.x and point.y contain screen coordinates rather than client coordinates. In screen coordinates, (0,0) corresponds to the upper left corner of the screen, the positive x and y axes point to the right and down, and one unit in any direction equals one pixel. If you want, you can convert screen coordinates to client coordinates with CWnd :: ScreenToClient . The nHitTest parameter contains a hit-test code that identifies where in the window's nonclient area the event occurred. Some of the most interesting hit-test codes are shown in the following table. You'll find a complete list of hit-test codes In The Documentation for WM_NCHITTEST or CWND :: Onnchittest.
Commonly Used Hit-Test Codes
ValueCorresponding LocationHTCAPTIONThe title barHTCLOSEThe close buttonHTGROWBOXThe restore button (same as HTSIZE) HTHSCROLLThe window's horizontal scroll barHTMENUThe menu barHTREDUCEThe minimize buttonHTSIZEThe restore button (same as HTGROWBOX) HTSYSMENUThe system menu boxHTVSCROLLThe window's vertical scroll barHTZOOMThe maximize buttonPrograms do not usually process nonclient-area mouse messages; they allow Windows to process them instead. Windows provides appropriate default responses that frequently result in still more messages being sent to the window. For example, when Windows processes a WM_NCLBUTTONDBLCLK message with a hit-test value equal to HTCAPTION, it sends the window a WM_SYSCOMMAND message with wParam equal to SC_MAXIMIZE or SC_RESTORE to maximize or unmaximize the window You can prevent double clicks on a title bar from affecting a window by including the following message handler in the window class.:
// in CMainWindow's Message Map
ON_WM_NCLBUTTONDBLCLK ()
Void CMainWindow :: OnnclButtondblclk (uint nhittest, cpoint point)
{
IF (nhittest! = htcaption)
CWnd :: ONNCLBUTTONDBLCLK (NHITTEST, POINT);
}
Calling the base class's OnNcLButtonDblClk handler passes the message to Windows and allows default processing to take place. Returning without calling the base class prevents Windows from knowing that the double click occurred. You can use other hit-test values to customize the window's response to other Nonclient-area mouse events.