The WM

zhaozj2021-02-17  44

The WM_NCHITTEST MESSAGE

Before a window receives a client-area or nonclient-area mouse message, it receives a WM_NCHITTEST message accompanied by the cursor's screen coordinates. Most applications do not process WM_NCHITTEST messages, instead electing to let Windows process them. When Windows processes a WM_NCHITTEST message , IT Uses The Cursor Coordinates To Determine What Part of The Window The Cursor Is over and the generates Either A Client-Area Or Nonclient-Area Mouse Message.

One Clever Use of An Onnchittest Handler Is for Substituting The Htcaption Hit-Test Code for HTClient, Which Creates A Window That Can Be Dragged by ITS Client Area:

// in CMainWindow's Message Map

ON_WM_NCHITTEST ()

Uint CMainWindow :: Onnchittest (cpoint point)

{

Uint nhittest = cframeWnd :: ONNCHITTEST (POINT);

IF (nhittest == htclient)

NHITTEST = HTCAPTION;

Return nhittest;

}

AS This Example Demonstrate, WM_Nchittest Messages That You don't process yourself should be forwarded to the base class so. Other assects of the program's operation aren't affected.

THE WM_MOUSELEAVE AND WM_MOUSEHOVER MESSAGES

It's easy to tell when the cursor enters a window or moves over it because the window receives WM_MOUSEMOVE messages. The :: TrackMouseEvent function, which debuted in Windows NT 4.0 and is also supported in Windows 98, makes it equally easy to determine when the cursor leaves a window or hovers motionlessly over the top of it. With :: TrackMouseEvent, an application can register to receive WM_MOUSELEAVE messages when the cursor leaves a window and WM_MOUSEHOVER messages when the cursor hovers over a window.

:: TrackMouseEvent ACCEPTS JUST One Parameter: a Poin TO A TRACKMOUSEEVENT STRUCTURE. The Structure IS Defined this way in winuser.h: typeef struct tagtrackmouseevent {

DWORD CBSIZE;

DWORD DWFLAGS;

HWND HWNDTRACK;

DWORD DWHOVERTIME;

TRACKMOUSEEVENT;

cbSize holds the size of the structure dwFlags holds bit flags specifying what the caller wants to do:. register to receive WM_MOUSELEAVE messages (TME_LEAVE), register to receive WM_MOUSEHOVER messages (TME_HOVER), cancel WM_MOUSELEAVE and WM_MOUSEHOVER messages (TME_CANCEL), or have the system fill the TRACKMOUSEEVENT structure with the current :: TrackMouseEvent settings (TME_QUERY). hwndTrack is the handle of the window for which WM_MOUSELEAVE and WM_MOUSEHOVER messages are generated. dwHoverTime is the length of time in milliseconds that the cursor must pause before a WM_MOUSEHOVER message is .

The cursor does not have to be perfectly still for the system to generate a WM_MOUSEHOVER message. If the cursor stays within a rectangle whose width and height equal the values ​​returned by :: SystemParametersInfo when it's called with SPI_GETMOUSEHOVERWIDTH and SPI_GETMOUSEHOVERHEIGHT values, and if it stays there for the number of milliseconds returned by :: SystemParametersInfo when it's called with an SPI_GETMOUSEHOVERTIME value, a WM_MOUSEHOVER message ensues. If you want, you can change these parameters by calling :: SystemParametersInfo with SPI_SETMOUSEHOVERWIDTH, SPI_SETMOUSEHOVERHEIGHT, and SPI_SETMOUSEHOVERTIME values.

One of the more interesting aspects of :: TrackMouseEvent is that its effects are cancelled when a WM_MOUSELEAVE or WM_MOUSEHOVER message is generated. This means that if you want to receive these message anytime the cursor exits or pauses over a window, you must call :: TrackMouseEvent again whenever a WM_MOUSELEAVE or WM_MOUSEHOVER message is received. to illustrate, the following code snippet writes "Mouse enter," "Mouse leave," or "Mouse hover" to the debug output window anytime the mouse enters, leaves, or pauses over a WINDOW. M_BMOUSEOVER IS A BOOL CMAINWINDOW MEMBER VARIABLE. It Should Be Set To False In The Class Construction: // in The Message Map

ON_WM_MOUSEMOVE ()

ON_MESSAGE (WM_MOUSELEAVE, ONMOUSELEAVE)

ON_MESSAGE (WM_Mousehover, OnMousehover)

Void CMainWindow :: ONMOUSEMOVE (uint nflags, cpoint point)

{

IF (! m_bmouseover) {

Trace (_T ("Mouse Enter / N"));

m_bmouseover = true;

TrackMouseEvent TME;

Tme.cbsize = Sizeof (TME);

Tme.dwflags = TME_HOVER | TME_LEVE;

Tme.hwndtrack = m_hwnd;

Tme.dwhovertime = Hover_Default;

:: TrackMouseEvent (& TME);

}

}

LResult CmainWindow :: OnMouseLeave (WPARAM WPARAM, LPARAM LPARAM)

{

Trace (_T ("mouse leave / n"));

m_bmouseover = false;

Return 0;

}

Lresult CMainWindow :: OnMousehover (WPARAM WPARAM, LPARAM LPARAM)

{

Trace (_T ("Mouse Hover (x =% D, Y =% D) / N"),

Loword (LPARAM), HiWord (LPARAM);

TrackMouseEvent TME;

Tme.cbsize = Sizeof (TME);

Tme.dwflags = TME_HOVER | TME_LEVE;

Tme.hwndtrack = m_hwnd;

Tme.dwhovertime = Hover_Default;

:: TrackMouseEvent (& TME);

Return 0;

}

MFC does not provide type-specific message-mapping macros for WM_MOUSELEAVE and WM_MOUSEHOVER messages, so as this example demonstrates, you must use the ON_MESSAGE macro to link these messages to class member functions. The lParam value accompanying a WM_MOUSEHOVER message holds the cursor's x coordinate in its low word and the cursor's y coordinate in its high word wParam is unused Both wParam and lParam are unused in WM_MOUSELEAVE messages.One final note regarding :: TrackMouseEvent:.. in order to use it, you must include the following #define IN your source code:

#define _win32_winnt 0x0400

Be Sure To include this line before the line what #includes afxwin.h. OtherWise, IT Will Have No Effect.

The Mouse Wheel

Many of the mice used with Windows today include a wheel that can be used to scroll a window without clicking the scroll bar. When the wheel is rolled, the window with the input focus receives WM_MOUSEWHEEL messages. MFC's CScrollView class provides a default handler for these Messages The Automatically Scrolls The Window, But if You Want Mouse Want Wheel Messages To Scroll A Non-CscrollView Window, You Must Process WM_MOUSEWHEEL Messages yourself.

MFC's ON_WM_MOUSEEL MACRO MAPS WM_MOUSEWHEEL Messages To The Message Handler OnMousewheel. OnMousewheel Is Prototyped Like this:

Bool OnMousewheel (Uint Nflags, Short Zdelta, Cpoint Point)

The nFlags and point parameters are identical to those passed to OnLButtonDown. ZDelta is the distance the wheel was rotated. A zDelta equal to WHEEL_DELTA (120) means the wheel was rotated forward one increment, or notch, and _WHEEL_DELTA means the wheel was rotated backward one notch. If the wheel is rotated forward five notches, the window will receive five WM_MOUSEWHEEL messages, each with a zDelta of WHEEL_DELTA. OnMouseWheel should return a nonzero value if it scrolled the window, or zero if it did not.A simple way to respond to a WM_MOUSEWHEEL message is to scroll the window one line up (if zDelta is positive) or one line down (if zDelta is negative) for every WHEEL_DELTA unit. The recommended approach, however, is slightly more involved. First you ask the system for the number of lines that corresponds to WHEEL_DELTA units. in Windows NT 4.0 and higher and in Windows 98, you can get this value by calling :: SystemParametersInfo with a first parameter equal to SPI_GETWHEELSCROLLL INES. Then you multiply the result by zDelta and divide by WHEEL_DELTA to determine how many lines to scroll. You can modify the Accel program presented in Chapter 2 to respond to WM_MOUSEWHEEL messages in this manner by adding the following message-map entry and message handler To CMAINWINDOW:

// in The Message Map

ON_WM_MOUSEWHEEL ()

Bool CmainWindow :: OnMousewheel (Uint Nflags, Short Zdelta, Cpoint Point)

{

Bool bup = true;

Int ndelta = zdelta;

IF (ZDELTA <0) {

BUP = false;

NDELTA = -ndelta;

}

Uint nwheelscrolllines;

:: SystemParametersInfo (SPI_Getwheelscroll Co., 0,

& nwheelscrollnes, 0);

IF (nwheelscrollnes == wheeel_pagescroll) {

SendMessage (WM_VSCROLL,

MakewParam (BUP? SB_PAGEUP: SB_PAGEDOWN, 0), 0);

Else {

INT nlines = (ndelta * nwheelscrollnes) / wheeel_delta;

While (nlines--)

SendMessage (WM_VSCROLL,

MakewParam (BUP? SB_LINEUP: SB_LINEDOWN, 0), 0);

}

Return True;

}

Dividing zDelta by WHEEL_DELTA ensures that the application will not scroll too quickly if, in the future, it's used with a mouse that has a wheel granularity less than 120 units. WHEEL_PAGESCROLL is a special value that indicates the application should simulate a click of the Scroll Bar Shaft-in Other Words, Perform A page-up or page-down. Both Wheel_Delta and wheel_pagescroll area defined in winuser.h.

One issue to be aware of regarding this code sample is that it's not compatible with Windows 95. Why Because calling :: SystemParametersInfo with an SPI_GETWHEELSCROLLLINES value does nothing in Windows 95. If you want to support Windows 95, you can either assume that?: : SystemParametersInfo would return 3 (the default) or resort to more elaborate means to obtain the user's preference MFC uses an internal function named _AfxGetMouseScrollLines to get this value _AfxGetMouseScrollLines is platform-neutral; it uses various methods to attempt to obtain a scroll line.. Count and defaults to 3ness. See the mfc source code file viewscrl.cpp if you'd like to mimic That Behavior in Your Code.

If the mouse wheel is clicked rather than rotated, the window under the cursor generally receives middle-button mouse messages-WM_MBUTTONDOWN messages when the wheel is pressed, WM_MBUTTONUP messages when the wheel is released. (I say "generally" because this is the default behavior;. it can be changed through the Control Panel) Some applications respond to wheel clicks in a special way Microsoft Word 97, for example, scrolls the currently displayed document when it receives WM_MOUSEMOVE messages with the wheel held down Knowing that the mouse.. Wheel Produces Middle-Button Messages, You Can Customize Your Applications To Respond To Mouse Wheel Events Any Way You See Fit.capturing The Mouse

One problem that frequently crops up in programs that process mouse messages is that the receipt of a button-down message does not necessarily mean that a button-up message will follow. Suppose you've written a drawing program that saves the point parameter passed to OnLButtonDown and uses it as an anchor point to draw a line whose other endpoint follows the cursor-an action known as "rubber-banding" a line. When a WM_LBUTTONUP message arrives, the application erases the rubber-band line and draws a real line in its place. But what happens if the user moves the mouse outside the window's client area before releasing the mouse button? The application never gets that WM_LBUTTONUP message, so the rubber-band line is left hanging in limbo and the real line isn ' T Drawn.

Windows provides an elegant solution to this problem by allowing an application to "capture" the mouse upon receiving a button-down message and to continue receiving mouse messages no matter where the cursor goes on the screen until the button is released or the capture is canceled . (In the Win32 environment, to prevent applications from monopolizing the mouse, the system stops sending mouse messages to a window that owns the capture if the button is released.) The mouse is captured with CWnd :: SetCapture and released with :: ReleaseCapture Calls to these Functions Are Normally Paired In Button-Down and Button-Up Handlers, As Shown Here: // In CMainWindow's Message Map

ON_WM_LBUTTONDOWN ()

ON_WM_LBUTTONUP ()

Void CMainWindow :: ONLBUTTONDOWN (Uint Nflags, Cpoint Point)

{

SetCapture ();

}

Void CMainWindow :: ONLBUTTONUP (uint nflags, cpoint point)

{

:: ReleaseCapture ();

}

In between, CMainWindow receives WM_MOUSEMOVE messages that report the cursor position even if the cursor leaves it. Client-area mouse messages continue to report cursor positions in client coordinates, but coordinates can now go negative and can also exceed the dimensions of the window's client area .

A related function, CWnd :: GetCapture, returns a CWnd pointer to the window that owns the capture. In the Win32 environment, GetCapture returns NULL if the mouse is not captured or if it's captured by a window belonging to another thread. The most common Use of getcapture is for determining WHether Your OWN WINDOW HAS CAPTURED THE. The Statement

GetCapture () == this)

IS true if and only if the window currently has the mouse captured.

How does capturing the mouse solve the problem with the rubber-banded line? By capturing the mouse in response to a WM_LBUTTONDOWN message and releasing it when a WM_LBUTTONUP message arrives, you're guaranteed to get the WM_LBUTTONUP message when the mouse button is released. The Sample Program in the next section illustrate the practical effect of this technique.mouse Capturing in action

The MouseCap application shown in Figure 3-4 is a rudimentary paint program that lets the user draw lines with the mouse. To draw a line, press the left mouse button anywhere in the window's client area and drag the cursor with the button held down. As the mouse is moved, a thin line is rubber-banded between the anchor point and the cursor. When the mouse button is released, the rubber-band line is erased and a red line 16 pixels wide is drawn in its place. Because the mouse is captured while the button is depressed, rubber-banding works even if the mouse is moved outside the window. and no matter where the cursor is when the mouse button is released, a red line is drawn between the anchor point and the endpoint. MouseCap's Source Code Appears in Figure 3-5.

Figure 3-4. The mousecap window.

Figure 3-5. The mousecap application.

Mousecap.hclass CMYAPP: Public CWINAPP

{

PUBLIC:

Virtual Bool InitInstance ();

}

Class CMainWindow: Public CFrameWnd

{

protected:

Bool m_btracking; // true if rubber banding

BOOL M_BCAPTUREENABED; / / TRUE IF CAPTURE ENABLED

Cpoint m_ptfrom; // "from" Point for Rubber Banding

Cpoint m_ptto; // "to" Point for Rubber Banding

Void Invertline (CDC * PDC, Cpoint PTFROM, CPOINT PTTO);

PUBLIC:

CMAINWINDOW ();

protected:

AFX_MSG Void ONLBUTTONDOWN (UINT NFLAGS, CPOINT); AFX_MSG Void ONLButtonup (uint nflags, cpoint point);

AFX_MSG Void OnMouseMove (uint nflags, cpoint point);

AFX_MSG Void OnnclButtondown (uint nhittest, cpoint point);

Declare_message_map ()

}

Mousecap.cpp # include

#include "mousecap.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, CFrameWnd)

ON_WM_LBUTTONDOWN ()

ON_WM_LBUTTONUP ()

ON_WM_MOUSEMOVE ()

ON_WM_NCLBUTTONDOWN ()

END_MESSAGE_MAP ()

CMAINWINDOW :: CMAINWINDOW ()

{

M_BTRACKING = FALSE;

m_bcaptureenabled = true;

//

// register a wndclass.

//

CString strwndclass = afxregisterWndclass (

0,

AFXGetApp () -> LoadStandardCursor (IDC_CROSS),

(Hbrush) (Color_Window 1),

AfxGetApp () -> LoadStandardon (IDI_WINLOGO)

);

//

// CREATE A WINDOW.

//

Create (StrWndClass, _T ("Mouse Capture Demo (Capture Enabled)))

}

Void CMainWindow :: ONLBUTTONDOWN (Uint Nflags, Cpoint Point)

{

//

// Record The Anchor Point and Set The Tracking Flag.

//

m_ptfrom = point;

m_PTTO = POINT;

M_BTRACKING = True;

//

// if Capture Is Enabled, Capture the Mouse.

//

IF (M_BCaptureEnable)

SetCapture ();

}

Void CMainWindow :: ONMOUSEMOVE (uint nflags, cpoint point)

{

//

// if the mouse is moved while we're "tracking" (That IS, while A

// line is being rubber-banded, ERASE the old rubber-band line and

// Draw a new one.

//

IF (m_btracking) {

CClientDC DC (this);

InvertLine (& DC, M_PTFROM, M_PTTO); InvertLine (& DC, M_PTFROM, POINT);

m_PTTO = POINT;

}

}

Void CMainWindow :: ONLBUTTONUP (uint nflags, cpoint point)

{

//

// if The Left Mouse Button Is Released While We're Tracking, RELEASE

// the mouse if it's currently captured, ERASE The Last Rubber-Band

// Line, And Draw A Thick Red Line In Its Place.

//

IF (m_btracking) {

M_BTRACKING = FALSE;

GetCapture () == this)

:: ReleaseCapture ();

CClientDC DC (this);

Invertline (& DC, M_PTFROM, M_PTTO);

CPEN PEN (PS_SOLID, 16, RGB (255, 0, 0));

Dc.selectObject (& Pen);

Dc.moveto (M_PTFROM);

Dc.Lineto (Point);

}

}

Void cmainwindow :: OnnclButtondown (uint nhittest, cpoint point)

{

//

//En the window's title bar is clickkeed with the left mouse button,

// Toggle The Capture Flag On or Off and Update The Window Title.

//

IF (nhittest == htcaption) {

m_bcaptureenabled = m_bcaptureenabled? false: True;

SETWINDOWTEXT (M_BCAPTUREENABLED?

_T ("Mouse Capture Demo (Capture Enabled)):

_T ("Mouse Capture Dyso (Capture Disabled))))

}

CframeWnd :: ONNCLBUTTONDOWN (NHITTEST, POINT);

}

Void CMainWindow :: InvertLine (CDC * PDC, Cpoint PTFROM, CPOINT PTTO)

{

//

// invert a line of pixels by Drawing a line in the r2_not drawing mode.

//

INT NOLDMODE = PDC-> setrop2 (r2_not);

PDC-> MoveTo (PTFROM);

PDC-> LINETO (PTTO);

PDC-> SETROP2 (NoldMode);

}

. Most of the action takes place in the program's OnLButtonDown, OnMouseMove, and OnLButtonUp handlers OnLButtonDown starts the drawing process by initializing a trio of variables that are members of the CMainWindow class:

m_ptfrom = point;

m_PTTO = POINT;

m_bTracking = TRUE; m_ptFrom and m_ptTo are the starting and ending points for the rubber-band line m_ptTo is continually updated by the OnMouseMove handler as the mouse is moved m_bTracking, which is TRUE when the left button is down and FALSE when it is.. NOT, IS A FLAG THAT TELLS ONMOUSEMOVE AND ONLBUTTONUP WHETHER A line is being rubber-banded. Onlbuttondown's only other action is to capture the mouse if m_bcaptureenabled is true:

IF (M_BCaptureEnable)

SetCapture ();

m_bCaptureEnabled is initialized to TRUE by CMainWindow's constructor. It is toggled by the window's OnNcLButtonDown handler so that you can turn mouse capturing on and off and see the effect that mouse capturing has on the program's operation. (More on this in a moment.)

ONMOUSEMOVE'S JOB IS to MOVE The Rubber-Band Line and Update M_Ptto with The New Cursor Position WHENEVER THE MOUSE IS MOVED. The Statement

Invertline (& DC, M_PTFROM, M_PTTO);

Erases The Previously Drawn Rubber-Band Line, And

Invertline (& DC, M_PTFROM, POIN);

draws a new one. InvertLine is a member of CMainWindow. It draws a line not by setting each pixel to a certain color, but by inverting the existing pixel colors. This ensures that the line can be seen no matter what background it is drawn against AND That Drawing the Line Again in The Same Location Will Erase It by Restoring The Original Screen Colors. The Inversion IS Accomplished by Setting The Device Context's Drawing Mode To R2_not with the Statement

INT NOLDMODE = PDC-> setrop2 (r2_not);

See Chapter 2 for a discussion of r2_not and other drawing modes.

When the left mouse button is released, CMainWindow :: OnLButtonUp is called After setting m_bTracking to FALSE and releasing the mouse, it erases the rubber-band line drawn by the last call to OnMouseMove:. CClientDC dc (this);

Invertline (& DC, M_PTFROM, M_PTTO);

ONLBUTTONUP THEN CREATES A SOLID Red Pen 16 Pixels Wide, Selects It Into The Device Context, and Draws A Thick Red Line:

CPEN PEN (PS_SOLID, 16, RGB (255, 0, 0));

Dc.selectObject (& Pen);

Dc.moveto (M_PTFROM);

Dc.Lineto (Point);

ITS Work Done, ONLBUTTONUP RETURns, And The Drawing Operation IS Complete. Figure 3-4 Above Shows What The Mousecap Window Looks LOKE AFTER A FEW LINES HAVE BEEN DRAWN AND As a new line is rubber-banded.

After you've played around with the program a bit, click the title bar to activate the OnNcLButtonDown handler and toggle the m_bCaptureEnabled flag from TRUE to FALSE. The window title should change from "Mouse Capture Demo (Capture Enabled)" to "Mouse Capture Demo (Capture Disabled). "OnNcLButtonDown processes left button clicks in the nonclient area and uses CWnd :: SetWindowText to change the window title if the hit-test code in nHitTest is equal to HTCAPTION, indicating that the click occurred in the title bar.

Now draw a few lines with mouse capturing disabled. Observe that if you move the mouse outside the window while rubber-banding, the line freezes until the mouse reenters the client area, and that if you release the mouse button outside the window, the program gets out of sync. The rubber-band line follows the mouse when you move it back to the interior of the window (even though the mouse button is no longer pressed), and it never gets erased. Click the title bar once again to reenable Mouse Capturing, And The Program Will Revert to Its Normal Self.The Cursor

Rather than use the arrow-shaped cursor you see in most Windows applications, MouseCap uses a crosshair cursor. Arrows and crosshairs are just two of several predefined cursor types that Windows places at your disposal, and if none of the predefined cursors fits the bill, You can Always Create Your Own. AS Usual, Windows Gives Programs A Great DEAL OF LATITITUDE IN this area.

First, a bit of background on how cursors work. As you know, every window has a corresponding WNDCLASS whose characteristics are defined in a WNDCLASS structure. One of the fields of the WNDCLASS structure is hCursor, which holds the handle of the class cursor- the image displayed when the cursor is over a window's client area. When the mouse is moved, Windows erases the cursor from its old location by redrawing the background behind it. Then it sends the window under the cursor a WM_SETCURSOR message containing a hit-test code. The system's default response to this message is to call :: SetCursor to display the class cursor if the hit-test code is HTCLIENT or to display an arrow if the hit-test code indicates that the cursor is outside the client area. As a result, the cursor is automatically updated as it is moved about the screen. When you move the cursor into an edit control, for example, it changes into a vertical bar or "I-beam" cursor. This happens because Windows registers a spec ial WNDCLASS for edit controls and specifies the I-beam cursor as the class cursor.It follows that one way to change the cursor's appearance is to register a WNDCLASS and specify the desired cursor type as the class cursor. In MouseCap, CMainWindow's constructor registers a WNDCLASS whose class cursor is idc_cross and passes the wndclass name to cframewnd :: Create:

CString strwndclass = afxregisterWndclass (

0,

AFXGetApp () -> LoadStandardCursor (IDC_CROSS),

(Hbrush) (Color_Window 1),

AfxGetApp () -> LoadStandardon (IDI_WINLOGO)

);

Create (StrWndClass, _T ("Mouse Capture Demo (Capture Enabled)))

Windows then displays a crosshair cursor anytime the mouse pointer is positioned in CMainWindow's client area.A second way to customize the cursor is to call the API function :: SetCursor in response to WM_SETCURSOR messages. The following OnSetCursor function displays the cursor whose handle is stored In CMainWindow :: M_Hcursor When The Cursor is over Cmainwindow's Client Area:

// in CMainWindow's Message Map

ON_WM_SETCURSOR ()

Bool CMainWindow :: OnsetCursor (CWND * PWND, UINT NHITTEST,

Uint Message)

{

IF (nhittest == htclient) {

:: setCursor (m_hcursor);

Return True;

}

Return CFrameWnd :: OnsetCursor (PWND, NHITTEST, Message);

}

Returning TRUE after calling :: SetCursor tells Windows that the cursor has been set. WM_SETCURSOR messages generated outside the window's client area are passed to the base class so that the default cursor is displayed. The class cursor is ignored because OnSetCursor never gives Windows the opportunity To display it.

Why would you want to use OnSetCursor rather than just registering m_hCursor as the class cursor? Suppose you want to display an arrow cursor when the cursor is in the top half of the window and an I-beam cursor when the cursor is in the bottom half . A class cursor will not suffice in this case, but OnSetCursor will do the job quite nicely The following OnSetCursor handler sets the cursor to either m_hCursorArrow or m_hCursorIBeam when the cursor is in CMainWindow's client area.:

Bool CMainWindow :: OnsetCursor (CWND * PWND, UINT NHITTEST,

Uint Message)

{

IF (nhittest == htclient) {

DWORD dwpos = :: getMessagePos ();

Cpoint Point (loword (dwpos), HiWord (dwpos));

ScreenToclient (& POINT);

CRECT RECT;

GetClientRect (& RECT);

:: setcursor ((Point.Y

m_hcursorarrow: m_hcursoribeam;

Return True;

}

Return CFrameWnd :: OnsetCursor (PWND, NHITTEST, Message);

}

:: GetMessagePos returns a DWORD value containing the cursor's x and y screen coordinates at the moment the WM_SETCURSOR message was retrieved from the message queue. CWnd :: ScreenToClient converts screen coordinates to client coordinates. If the converted point's y coordinate is less than half the height of the window's client area, the cursor is set to m_hCursorArrow. But if y is greater than or equal to half the client area height, the cursor is set to m_hCursorIBeam instead. The VisualKB application presented later in this chapter uses a similar technique to .

SHOULD The Need Ever Arise, You Can Hide The Cursor with the statement

:: Showcursor (false);

And Display It Again with

:: Showcursor (True);

Internally, Windows maintains a display count that's incremented each time :: ShowCursor (TRUE) is called and decremented by each call to :: ShowCursor (FALSE). The count is initially set to 0 if a mouse is installed and to -1 if no mouse is present, and the cursor is displayed whenever the count is greater than or equal to 0. Thus, if you call :: ShowCursor (FALSE) twice to hide the cursor, you must call :: ShowCursor (TRUE) twice to display it Again.

The Hourglass Cursor

When an application responds to a message by undertaking a lengthy processing task, it's customary to change the cursor to an hourglass to remind the user that the application is "busy." (While a message handler executes, no further messages are retrieved from the message queue and the program is frozen to input In Chapter 17, you'll learn about ways to perform background processing tasks while continuing to retrieve and dispatch messages) Windows provides the hourglass cursor for you;... its identifier is IDC_WAIT An easy way to Display An Hourglass Cursor Is To Declare A CWAITCURSOR VARIABLE ON The Stack, Like this:

CWAITCURSOR WAIT;

. CWaitCursor's constructor displays an hourglass cursor, and its destructor restores the original cursor If you'd like to restore the cursor before the variable goes out of scope, simply call CWaitCursor :: Restore:

Wait.Restore ();

You Should Call Restore Before Taking Any Action That Would Allow A WM_SETCURSOR Message to Seep Through and destroy the Hourglass-for Example, Before Displaying a Message Box OR a Dialog Box.

You can change the cursor displayed by CWaitCursor :: CWaitCursor and BeginWaitCursor by overriding CWinApp's virtual DoWaitCursor function. Use the default implementation of CWinApp :: DoWaitCursor found in the MFC source code file Appui.cpp as a model for your own implementations.

Mouse miscellanea

As mentioned earlier, calling the :: GetSystemMetrics API function with an SM_CMOUSEBUTTONS argument queries the system for the number of mouse buttons. (There is no MFC equivalent to :: GetSystemMetrics, so you must call it directly.) The usual return value is 1 , 2, OR 3, But A 0 Return Means No Mouse Is Attached. You Can Also Find Out WHETHER A MOUSESYSTEMTRICS (SM_MOUSEPRESENT)

The return value is nonzero if there is a mouse attached, 0 if there is not. In the early days of Windows, programmers had to consider the possibility that someone might be using Windows without a mouse. Today that's rarely a concern, and a program That queries the system to determine WHETHER A MOUSE IS Present is a rare program indeed.

Other mouse-related :: GetSystemMetrics parameters include SM_CXDOUBLECLK and SM_CYDOUBLECLK, which specify the maximum horizontal and vertical distances (in pixels) that can separate the two halves of a double click, and SM_SWAPBUTTON, which returns a nonzero value if the user has swapped the left and right mouse buttons using the Control Panel. When the mouse buttons are swapped, the left mouse button generates WM_RBUTTON messages and the right mouse button generates WM_LBUTTON messages. Generally you do not need to be concerned about this, but if for some reason Your Application Wants To Be Sure That The Left Mouse Button, IT CAN Use :: getSystemMetrics To Determine WHether The Buttons Have Been Swapped.

The API functions :: SetDoubleClickTime and :: GetDoubleClickTime enable an application to set and retrieve the mouse double-click time-the maximum amount of time permitted between clicks when a mouse button is double-clicked. The expression :: GetDoubleClickTime ()

Returns the double-click time in Milliseconds, While The Statement

:: setDoubleClicktime (250);

sets the double-click time to 250 milliseconds, or one quarter of a second. When the same mouse button is clicked twice in succession, Windows uses both the double-click time and the SM_CXDOUBLECLK and SM_CYDOUBLECLK values ​​returned by :: GetSystemMetrics to determine whether To Report The Second of The Two ClickS as a Double Click.

A function that processes mouse messages can determine which, if any, mouse buttons are pressed by checking the nFlags parameter passed to the message handler. It's also possible to query the state of a mouse button outside a mouse message handler by calling :: GetKeyState or :: GetAsyncKeyState with a VK_LBUTTON, VK_MBUTTON, or VK_RBUTTON parameter. :: GetKeyState should be called only from a keyboard message handler because it returns the state of the specified mouse button at the time the keyboard message was generated. :: GetAsyncKeyState can be called Anywhere, Anytime. It works in real time, return the state of the button at the moment the function is called. a NEGATIVE RETURN VALUE FROM

:: getKeyState (vk_lbutton)

oral

:: GetasyncKeyState (vk_lbutton)

indicates that the left mouse button is pressed. Swapping the mouse buttons does not affect :: GetAsyncKeyState, so if you use this function, you should also use :: GetSystemMetrics to determine whether the buttons have been swapped. The expression

:: getasynckeystate (: getSystemMetrics (sm_swapbutton)? Vk_rbutton: vk_lbutton

Checks The State of The Left Mouse Button Asynchronously and Automatical Queries The Right Mouse Button INSTONSTON INSTON INSTONSETON SWAPPED.

Windows provides a pair of API functions named :: GetCursorPos and :: SetCursorPos for getting and setting the cursor position manually. :: GetCursorPos copies the cursor coordinates to a POINT structure. A related function named :: GetMessagePos returns a DWORD value containing a pair Of 16-bit Coordinates Specifying Where The Cursor Was When The last message que. You can Extract Those Coordinates Using The Windows Loword and HiWord Macros:

DWORD dwpos = :: getMessagePos ();

INT x = loword (dwpos);

INT Y = HiWord (dwpos);

:: getMESSORPOS AND:: GetMessagePos Both Report The Cursor Position in Screen Coordinates. Screen Coordinates CAN Be Converted to Client Coordinates by Calling A Window's ClientToscreen Function.

Windows also provides a function named :: ClipCursor that restricts the cursor to a particular area of ​​the screen. :: ClipCursor accepts a pointer to a RECT structure that describes, in screen coordinates, the clipping rectangle. Since the cursor is a global resource shared By All Applications, An Application That Uses :: Clipcursor Must Free The Cursor by Calling

:: Clipcursor (NULL);

BEFORE TERMINATING, OR Else The Cursor Will Remain Locked INTO The Clipping Rectangle Indefinitely.

转载请注明原文地址:https://www.9cbs.com/read-30678.html

New Post(0)