The Clock Application
The Clock application shown in Figure 14-1 uses a timer set to fire at 1-second intervals to periodically redraw a set of clock hands simulating an analog clock Clock is not a document / view application;. It uses the MFC 1.0_style application architecture described in the first few chapters of this book. All of its source code, including the RC file, was generated by hand. (See Figure 14-2.) Besides demonstrating how to use a timer in a Windows application, Clock introduces a New MFC Class Named CTIME AND A New Message, WM_MINMAXINFO. IT Also Has Several Other Interesting Features That Have Nothing to do with Timers, Including Thase:
A command in the system menu for removing the window's title bar A command in the system menu for making Clock's window a topmost window-one that's drawn on top of other windows even when it's running in the background A persistent frame window that remembers its size and Position a frame window That Can Be Dragged by ITS Client Area
We'll Go Over these and other unique assects of the application in the section. Follow.
Figure 14-1. The clock window.
Figure 14-2. The clock application.
Resource.h # define idm_sysmenu_full_window 16
#define idm_sysmenu_stay_on_top 32
#define idi_appicon 100
Clock.rc # incrude
#include "resource.h"
IDI_APPICON ICON CLOCK.ICO
Clock.hclass CMYAPP: Public CWINAPP
{
PUBLIC:
Virtual Bool InitInstance ();
}
Class CMainWindow: Public CFrameWnd
{
protected:
Bool m_bfullwindow;
BOOL M_BSTAYONTOP;
INT m_nprevsecond;
INT m_nprevminute;
INT M_NPREVHOUR;
Void DrawClockface (CDC * PDC);
Void DrawSecondHand (CDC * PDC, Int Nlength, Int NScale, Int Ndegrees, ColorRef Clrcolor);
Void Drawhand (CDC * PDC, Int Nlength, Int Nscale, Int Ndegrees,
ColorRef clrcolor;
Void setTitlebarstate ();
Void settopmostState ();
Void savewindowstate ();
Void UpdateSystemMenu (cmenu * pmenu);
PUBLIC:
CMAINWINDOW ();
Virtual Bool PrecreateWindow (CreateStruct & Cs);
Bool restorewindowstate ();
protected:
AFX_MSG Int Oncreate (LPCReatestruct LPCS);
AFX_MSG Void ONGETMAXINFO (MinMaxInfo * PMMI);
AFX_MSG Void Ontimer (uint ntimerid);
AFX_MSG void onpaint ();
AFX_MSG uint onnchittest (cpoint point);
AFX_MSG Void OnSysCommand (Uint Nid, LParam Lparam);
AFX_MSG Void OnContextMenu (CWND * PWND, CPOINT);
AFX_MSG Void OneendSession (Bool Bending);
AFX_MSG void onclose ();
Declare_message_map ()
}
Clock.cpp # include
#include
#include "clock.h"
#include "resource.h"
#define SquareSize 20
#define id_timer_clock 1
CMYAPP myApp;
/
// CMYAPP Member Functions
Bool CmyApp :: InitInstance ()
{
SetRegistryKey (_T ("Programming Windows With MFC");
m_pmainwnd = new cmainwindow;
IF (! (cmainwindow *) m_pmainwnd) -> restoreWindowState ())
m_pmainwnd-> showwindow (m_ncmdshow);
m_pmainwnd-> UpdateWindow ();
Return True;
}
/
// CMainWindow Message Map and Member Functions
Begin_MESSAGE_MAP (CMainWindow, CFrameWnd)
ON_WM_CREATE ()
ON_WM_PAINT ()
ON_WM_TIMER ()
ON_WM_GETMINMAXINFO ()
ON_WM_NCHITTEST ()
ON_WM_SYSCOMMAND ()
ON_WM_CONTEXTMENU ()
ON_WM_ENDSession ()
ON_WM_CLOSE ()
END_MESSAGE_MAP ()
CMAINWINDOW :: CMAINWINDOW ()
{
m_bautomenuenable = false;
CTIME TIME = CTIME :: getcurrenttime ();
m_nprevsecond = Time.getSecond (); m_nprevminute = time.getminute ();
m_nprevhour = time.getHour ()% 12;
CString strwndclass = afxregisterWndclass (
CS_HREDRAW œ CS_VREDRAW,
MyApp.loadStandardcursor (IDC_ARROW),
(Hbrush) (color_3dface 1),
myapp.loadicon (IDI_Appicon));
Create (strwndclass, _t ("clock");
}
Bool CMainWindow :: PrecreateWindow (CreateStruct & Cs)
{
IF (! cframeWnd :: PrecreateWindow (CS))
Return False;
Cs.dwexStyle & = ~ ws_ex_cliented;
Return True;
}
INT CMAINWINDOW :: OnCreate (lpcreatestruct lpcs)
{
IF (cframewnd :: oncreate (lpcs) == -1)
Return -1;
//
// set a Timer to Fire At 1-Second Intervals.
//
IF (! settimer (id_timer_clock, 1000, null) {
MessageBox (_t ("settimer failed"), _t ("error"),
MB_ICONSTOP œ MB_OK);
Return -1;
}
//
// Customize The System Menu.
//
CMenu * pmenu = getSystemMenu (false);
Pmenu-> appendmenu (mf_separator);
Pmenu-> appendmenu (mf_string, idm_sysmenu_full_window,
_T ("remove & title");
PMenu-> appendmenu (mf_string, idm_sysmenu_stay_on_top,
_T ("Stay on To & P"));
Return 0;
}
Void cmainwindow :: onClose ()
{
SaveWindowState ();
KillTimer (ID_TIMER_CLOCK);
CframeWnd :: onClose ();
}
Void CMainWindow :: OnendSession (Bool Bending)
{
IF (bending)
SaveWindowState ();
CframeWnd :: OneendSession (Bending);
}
Void CMainWindow :: ONGETMINMAXINFO (MinMaxInfo * PMMI)
{
PMMI-> ptmintracksize.x = 120;
PMMI-> ptmintracksize.y = 120;
}
Uint CMainWindow :: Onnchittest (cpoint point)
{
Uint nhittest = cframeWnd :: ONNCHITTEST (POINT);
IF ((nhittest == htclient) && (: getasynckeystate (mk_lbutton) <0)))
NHITTEST = HTCAPTION; RETURN NHITTEST;
}
Void CMainWindow :: OnsysCommand (uint nid, lparam lparam)
{
UINT nmasKedid = NID & 0xFFF0;
IF (nmasKedid == idm_sysmenu_full_window) {
m_bfullwindow = m_bfulwindow? 0: 1;
Settitlebarstate ();
Return;
}
Else IF (nmaskedid == idm_sysmenu_stay_on_top) {
M_BSTAYONTOP = m_bstayontop? 0: 1;
SettopmostState ();
Return;
}
CframeWnd :: OnSysCommand (NID, LPARAM);
}
Void CMainWindow :: onContextMenu (CWND * PWND, CPOINT POINT)
{
CRECT RECT;
GetClientRect (& RECT);
Clienttoscreen (& Re);
IF (Rect.ptinRect (POINT)) {
CMenu * pmenu = getSystemMenu (false);
UpdateSystemMenu (Pmenu);
INT NID = (int) pMenu-> TRACKPOPUPMENU (TPM_LEFTALIGN œ
TPM_LEFTBUTTON œ TPM_RightButton œ TPM_RETURNCMD, POINT.X,
Point.y, this);
IF (NID> 0)
SendMessage (WM_SYSCOMMAND, NID, 0);
Return;
}
CframeWnd :: OnContextMenu (PWND, POINT);
}
Void CMainWindow :: ONTIMER (Uint Ntimerid)
{
//
// do Nothing if the window is minimized.
//
IF (Isiconic ())
Return;
//
// Get The Current Time and Do Not IT Hasn't Changed.
//
CTIME TIME = CTIME :: getcurrenttime ();
INT nsecond = time.getSecond ();
INT nminute = time.getminute ();
INT NHOUR = Time.Gethour ()% 12;
IF ((nsecond == m_nprevsecond) &&
(nminute == m_nprevminute) &&
(NHOUR == m_nprevhour))
Return;
//
// Center the Origin and Switch To The mm_isotropic mapping mode.
//
CRECT RECT;
GetClientRect (& RECT);
CClientDC DC (this);
Dc.SETMAPMODE (mm_isotropic);
Dc.SetWindowExt (1000, 1000);
Dc.setViewPortext (Rect.width (), -Rect.Height ());
Dc.SetViewportorg (Rect.width () / 2, Rect.Height () / 2);
//
// if minutes have changed, Erase the Hour and minute hand.
//
ColorRef CLRCOLOR = :: getSyscolor (color_3dface);
IF (nminute! = m_nprevminute) {
DrawHand (& DC, 200, 4, (M_NPRevhour * 30) (m_nprevminute / 2),
CLRCOLOR);
DrawHand (& DC, 400, 8, M_NPREvminute * 6, CLRCOLOR);
m_nprevminute = nminute;
m_nprevhour = NHOUR;
}
//
// if Seconds Have Changed, Erase The Second Hand and RedRaw All Hands.
//
IF (nsecond! = m_nprevsecond) {
Drawsecondhand (& DC, 400, 8, M_NPREVSECOND * 6, CLRCOLOR);
DrawSecondHand (& DC, 400, 8, NSECOND * 6, RGB (0, 0, 0));
DrawHand (& DC, 200, 4, (NHOUR * 30) (nminute / 2),
RGB (0, 0, 0));
Drawhand (& DC, 400, 8, Nminute * 6, RGB (0, 0, 0));
m_nprevsecond = nsecond;
}
}
Void cmainwindow :: onpaint ()
{
CRECT RECT;
GetClientRect (& RECT);
CPAINTDC DC (this);
Dc.SETMAPMODE (mm_isotropic);
Dc.SetWindowExt (1000, 1000);
Dc.setViewPortext (Rect.width (), -Rect.Height ());
Dc.SetViewportorg (Rect.width () / 2, Rect.Height () / 2);
DrawClockface (& DC);
DrawHand (& DC, 200, 4, (M_nprevhour * 30)
(m_nprevminute / 2), RGB (0, 0, 0));
DrawHand (& DC, 400, 8, M_NPREVMINUTE * 6, RGB (0, 0, 0));
DrawSecondHand (& DC, 400, 8, M_NPREVSECOND * 6, RGB (0, 0, 0));
}
Void CMainWindow :: DrawClockface (CDC * PDC)
{
Static Cpoint Point [12] = {
Cpoint (0, 450), // 12 O'Clock
Cpoint (225, 390), // 1 O'Clock
Cpoint (390, 225), // 2 O'Clock
Cpoint (450, 0), // 3 O'Clock
Cpoint (390, -225), // 4 O'Clock
Cpoint (225, -390), //5 O'Clock
Cpoint (0, -450), // 6 O'Clock
Cpoint (-225, -390), //7 O'Clock
CPOINT (-390, -225), // 8 O'Clockcpoint (-450, 0), // 9 O'Clock
CPOINT (-390, 225), // 10 O'Clock
CPOINT (-225, 390), // 11 O'Clock
}
PDC-> SelectStockObject (null_brush);
For (int i = 0; i <12; i )
PDC-> Rectangle (Point [i] .x - Squaresis,
Point [i] .y squaresis, point [i] .x squareesize,
Point [i] .y - squaresis;
}
Void CMainWindow :: DrawHand (CDC * PDC, Int Nlength, Int Nscale,
Int Ndegrees, ColorRef Clrcolor
{
CPoint Point [4];
Double nradians = (double) ndegrees * 0.017453292;
Point [0] .x = (int) (NRADIANS);
Point [0] .y = (int));
Point [2] .x = -point [0] .x / nscale;
Point [2] .y = -point [0] .y / nscale;
Point [1] .x = -point [2] .y;
Point [1] .y = point [2] .x;
Point [3] .x = -point [1] .x;
Point [3] .y = -point [1] .y;
CPEN PEN (PS_SOLID, 0, CLRCOLOR);
CPEN * POLDPEN = PDC-> SELECTOBJECT (& PEN);
PDC-> MoveTo (Point [0]);
PDC-> Lineto (Point [1]);
PDC-> LineTo (Point [2]);
PDC-> LineTo (Point [3]);
PDC-> LineTo (Point [0]);
PDC-> SELECTOBJECT (POLDPEN);
}
Void CMainWindow :: DrawSecondHand (CDC * PDC, Int Nlength, Int Nscale,
Int Ndegrees, ColorRef Clrcolor
{
CPoint Point [2];
Double nradians = (double) ndegrees * 0.017453292;
Point [0] .x = (int) (NRADIANS);
Point [0] .y = (int));
Point [1] .x = -point [0] .x / nscale;
Point [1] .y = -point [0] .y / nscale;
CPEN PEN (PS_SOLID, 0, CLRCOLOR);
CPEN * POLDPEN = PDC-> SELECTOBJECT (& PEN);
PDC-> MoveTo (Point [0]);
PDC-> Lineto (Point [1]);
PDC-> SELECTOBJECT (POLDPEN);
}
Void cmainwindow :: settitlebarstate ()
{
CMenu * pmenu = getSystemMenu (false); if (m_bfulwindow) {
ModifyStyle (WS_CAPTION, 0);
Pmenu-> modifymenu (idm_sysmenu_full_window, mf_string,
IDM_SYSMENU_FULL_WINDOW, _T ("Restore & Title");
}
Else {
ModifyStyle (0, WS_CAPTION);
Pmenu-> modifymenu (idm_sysmenu_full_window, mf_string,
IDM_SYSMENU_FULL_WINDOW, _T ("Remove & Title");
}
SetWindowPos (NULL, 0, 0, 0, 0, SWP_NOMOVE œ SWP_NOSIZE œ
SWP_NOZORDER œ SWP_DRAWFRAME);
}
Void cmainwindow :: settopmostState ()
{
CMenu * pmenu = getSystemMenu (false);
IF (M_BSTAYONTOP) {
SetwindowPOS (& Wndtopmost, 0, 0, 0, 0, SWP_NOMOVE œ SWP_NOSIZE);
PMenu-> CheckMenuItem (IDM_SYSMENU_STAY_ON_TOP, MF_CHECKED);
}
Else {
SetwindowPos (& Wndnotopmost, 0, 0, 0, 0, SWP_NOMOVE œ SWP_NOSIZE);
PMenu-> CheckMenuItem (IDM_SYSMENU_STAY_ON_TOP, MF_UNCHECKED);
}
}
Bool cmainwindow :: restoreWindowState ()
{
CSTRING VERSION = _T ("Version 1.0");
m_bfulwindow = myapp.getprofileint (Version, _T ("fullwindow"), 0);
Settitlebarstate ();
m_bstayontop = myapp.getprofileint (Version, _t ("stayontop"), 0);
SettopmostState ();
WindowPlacement WP;
WP.Length = SizeOf (Windowplacement);
GetWindowPlacement (& WP);
IF ((wp.flags =
MyApp.getProfileint (Version, _T ("flags"), -1))! = -1) &&
((wp.showcmd =
Myapp.getprofileint (Version, _T ("showcmd"), -1)))! = -1) &&
((wp.rcnormalposition.left =
MyApp.getProfileint (Version, _T ("x1"), -1)))! = -1) &&
((wp.rcnormalposition.top =
Myapp.getprofileint (Version, _T ("Y1"), -1))! = -1) &&
((wp.rcnormalposition.right=right=
MyApp.getProfileint (Version, _T ("x2"), -1))! = -1) && ((wp.rcnormalposition.bottom =
MyApp.getProfileint (Version, _T ("Y2"), -1))! = -1)) {
wp.rcnorMalPosition.Left = min (wp.rcnormalposition.left,
:: getSystemMetrics - -
:: GetSystemMetrics (SM_CXICON));
wp.rcnormalPosition.top = min (wp.rcnormalposition.top,
:: GetSystemMetrics (SM_CYSCREEN) -
:: getSystemMetrics (SM_CYICON));
SetwindowPlacement;
Return True;
}
Return False;
}
Void cmainwindow :: saveWindowState ()
{
CSTRING VERSION = _T ("Version 1.0");
MyApp.WriteProfileint (Version, _T ("fullwindow"), m_bfulwindow);
MyApp.writeprofileint (Version, _T ("stayontop"), m_bstayontop);
WindowPlacement WP;
WP.Length = SizeOf (Windowplacement);
GetWindowPlacement (& WP);
MyApp.WriteProfileint (Version, _T ("flags"), wp.flags;
Myapp.writeprofileint (Version, _T ("showcmd"), wp.showcmd;
MyApp.WriteProfileint (Version, _t ("x1"), wp.rcnormalposition.Left);
MyApp.writeprofileint (Version, _T ("Y1"), wp.rcnormalposition.top;
MyApp.WriteProfileint (Version, _t ("x2"), wp.rcnormalposition.right;
MyApp.WriteProfileint (Version, _T ("Y2"), wp.rcnorMalposition.bottom
}
Void CMainWindow :: UpdateSystemMenu (cmenu * pmenu)
{
Static uint nState [2] [5] = {
{MFS_GRAYED, MFS_ENABLED, MFS_ENABLED,
MFS_ENABLED, MFS_DEFAULT},
{MFS_DEFAULT, MFS_GRAYED, MFS_GRAYED,
MFS_ENABLED, MFS_GRAYED}
}
IF (Isiconic ()) // Shouldn't Happen, But Let's Be Safe
Return;
INT i = 0;
IF (iszoomed ())
i = 1;
Cstring strmenutext;
Pmenu-> getmenustring (sc_restore, stridentext, mf_bycommand);
Pmenu-> modifymenu (sc_restore, mf_string œ nstate [i] [0], sc_restore, strmenutext);
Pmenu-> getmenustring (sc_move, stridentext, mf_bycommand);
Pmenu-> modifymenu (sc_move, mf_string œ nstate [i] [1], sc_move,
Strmenutext);
Pmenu-> getmenustring (sc_size, stridentext, mf_bycommand);
Pmenu-> modifymenu (sc_size, mf_string œ nstate [i] [2], sc_size,
Strmenutext);
Pmenu-> getmenustring (sc_minimize, strident, mf_bycommand);
Pmenu-> modifymenu (sc_minimize, mf_string œ nState [i] [3], sc_minimize,
Strmenutext);
Pmenu-> getmenustring (sc_maximize, strident, mf_bycommand);
Pmenu-> modifymenu (sc_maximize, mf_string œ nState [i] [4], sc_maximize,
Strmenutext);
SetmenudeFaultItem (pmenu-> m_hmenu, i? Sc_restore:
SC_Maximize, False;
}
Processing Timer Messages
Clock uses SetTimer to program a timer in OnCreate. The timer is destroyed in OnClose with KillTimer. When a WM_TIMER message arrives, CMainWindow :: OnTimer gets the current time and compares the hour, minute, and second to the hour, minute, and second previously recorded in the member variables m_nPrevHour, m_nPrevMinute, and m_nPrevSecond. If the current hour, minute, and second equal the hour, minute, and second recorded earlier, OnTimer does nothing. Otherwise, it records the new time and moves the clock hands. . CMainWindow :: DrawHand draws the hour and minute hands, and CMainWindow :: DrawSecondHand draws the second hand A hand is moved by calling the corresponding drawing function twice: once to erase the hand by drawing over it with the window background color (COLOR_3DFACE) And Once to Draw The Hand-in Black-in Its New Position.
With this OnTimer mechanism in place, the clock's second hand is moved roughly once per second and the hour and minute hands are moved whenever the current number of minutes past the hour no longer equals the previously recorded minutes-past-the-hour. Because the hands are drawn to reflect the current time and not some assumed time based on the number of WM_TIMER messages received, it does not matter if WM_TIMER messages are skipped as the window is dragged or resized. If you watch closely, you'll see that the second hand occasionally advances by two seconds rather than one. That's because every now and then a WM_TIMER message arrives just before a new second ticks off and the next WM_TIMER message arrives a split second after the next new second. You could prevent this from happening by lowering the timer interval to, say, 0.5 second. The cost would be more overhead to the system, but the added overhead would be minimal because OnTimer is structured so that it redraws the clock hands ( .
Before doing anything else, OnTimer calls the main window's IsIconic function to determine whether the window is currently minimized. IsIconic returns nonzero for a minimized window and 0 for an unminimized window. (A complementary function, CWnd :: IsZoomed, returns a nonzero value if a window is maximized and 0 if it is not.) If IsIconic returns nonzero, OnTimer exits immediately to prevent the clock display from being updated when the window is not displayed. When a minimized window calls GetClientRect in Windows 95 or higher or Windows NT 4.0 or higher, the returned rectangle is a NULL rectangle-one whose coordinates equal 0. The application can try to paint in this rectangle, but the GDI will clip the output. Checking for a minimized window upon each timer tick reduces the load on THE CPU by Eliminating Unnecessary Drawing.if You'D Rather That Clock Not Sit iDLETLE ITS WINDOW Is Minimized, Try Rewriting The Beginning of The Ontimer Function So That Looks Like this:
CTIME TIME = CTIME :: getcurrenttime ();
INT nsecond = time.getSecond ();
INT nminute = time.getminute ();
INT NHOUR = Time.Gethour ()% 12;
IF (isiconic ()) {
CString Time;
Time.format (_T ("% 0.2d:% 0.2d: 0.2d"), NHOUR, NMINUTE, NSECOND);
SetWindowText (Time);
Return;
}
Else {
SetWindowText (_t ("clock"));
}
An application can change the text displayed next to its icon in the taskbar by changing the window title with CWnd :: SetWindowText. If modified as shown above, Clock will tick off the seconds in the taskbar while it is minimized.
Getting The Current Time: The Ctime Class
To query the system for the current time, Clock uses a CTime object. CTime is an MFC class that represents times and dates. It includes convenient member functions for getting the date, time, day of the week (Sunday, Monday, Tuesday, and . so on), and other information Overloaded operators such as , -, and> allow you to manipulate times and dates with the ease of simple integers.The CTime member functions that interest us are GetCurrentTime, which is a static function that returns a CTime object initialized to the current date and time; GetHour, which returns the hour (0 through 23); GetMinute, which returns the number of minutes past the hour (0 through 59); and getSecond, which returns the number of seconds (0 THROUGH 59). Ontimer Uses The Following Statements to Retrieve The Current Hour, Minute, And Second So That Can Determine WHether The Clock Display Needs to Be Updated:
CTIME TIME = CTIME :: getcurrenttime ();
INT nsecond = time.getSecond ();
INT nminute = time.getminute ();
INT NHOUR = Time.Gethour ()% 12;
The modulo-12 operation applied to GetHour's return value converts the hour to an integer from 0 through 11. CMainWindow's constructor uses similar code to initialize m_nPrevHour, m_nPrevMinute, and m_nPrevSecond.
Using the mm_isotropic mapping mode
Up to now, most of the applications that we've developed have used the default MM_TEXT mapping mode. The mapping mode governs how Windows converts the logical units passed to CDC drawing functions into device units (pixels) on the display. In the MM_TEXT mapping mode, logical units and device units are one and the same, so if an application draws a line from (0,0) to (50,100), the line extends from the pixel in the upper left corner of the display surface to the pixel that lies 50 pixels to the right of and 100 pixels below the upper left corner. This assumes, of course, that the drawing origin has not been moved from its default location in the upper left corner of the display surface.MM_TEXT is fine for most applications, but you can use other GDI mapping modes to lessen an application's dependency on the physical characteristics of the display. (for a review of GDI mapping modes, refer to Chapter 2.) In the MM_LOENGLISH mapping mode, for example, one logical unit Is equal to 1/100 of an inch, so if you want to draw a line exactly 1 inch long, you can use a length of 100 units and Windows will factor in the number of pixels per inch when it scan-converts the line into pixels. The conversion might not be perfect for screen DCs because Windows uses assumed pixel-per-inch values for screens that are not based on the physical screen size. Windows can obtain precise pixel-per-inch values for printers and other hardcopy devices, however, so by using MM_LOENGLISH For Printer Output, You Really CAN Draw A Line 1 Inch Long.
Clock uses the MM_ISOTROPIC mapping mode, in which logical units measured along the x axis have the same physical dimensions as logical units measured along the y axis. Before drawing the clock's face and hands in response to a WM_TIMER or WM_PAINT message, Clock measures the window's client area with GetClientRect and creates a device context. Then it sets the mapping mode to MM_ISOTROPIC, moves the origin of the coordinate system so that the logical point (0,0) lies at the center of the window's client area, and sets the window Extents So That The Window's Client Area MeasureS 1,000 Logical Units in Each Direction. Here'S HOW IT LOOKS IN CODE: CRECT RECT
GetClientRect (& RECT);
CclientDC DC (this); // in onpaint, use cpaintdc instead.
Dc.SETMAPMODE (mm_isotropic);
Dc.SetWindowExt (1000, 1000);
Dc.setViewPortext (Rect.width (), -Rect.Height ());
Dc.SetViewportorg (Rect.width () / 2, Rect.Height () / 2);
The negative value passed to SetViewportExt specifying the viewport's physical height orients the coordinate system such that values of y increase in the upward direction. If the negative sign were omitted, increasing values of y would move down the screen rather than up because Windows numbers pixels at the bottom of the screen higher than it does pixels at the top. Figure 14-3 shows what the coordinate system looks like after it is transformed. The coordinate system is centered in the window's client area, and values of x and y increase as you .
Figure 14-3. Clock's Coordinate System for Screen Output.
Once you've configured the coordinate system this way, you can write the routines that draw the clock's face and hands without regard for the physical dimensions of the window. When DrawHand is called to draw a clock hand, the length value passed in the second parameter is either 200 for an hour hand or 400 for a minute hand. DrawSecondHand, too, is passed a length of 400. Because the distance from the origin of the coordinate system to any edge of the window is 500 logical units, the minute and second hands extend outward 80 percent of the distance to the nearest window edge and the hour hand spans 40 percent of the distance. If you used the MM_TEXT mapping mode instead, you'd have to scale every coordinate and every distance manually before passing it to The gdi.hiding and displaying the title bar
Clock's system menu contains two extra commands:.. Remove Title and Stay On Top Remove Title removes the window's title bar so that the clock face fills the entire window You can restore the title bar by displaying the system menu again and selecting Restore Title, which appears where Remove title used to be. The magic underlying this transformation is simple, yet adding or removing a title bar on the fly is enough to make even seasoned Windows programmers scratch their heads in bewilderment the first time they try it.
The secret lies in CMainWindow :: SetTitleBarState. The attribute that determines whether a window has a title bar is the WS_CAPTION style bit, which is included in the WS_OVERLAPPEDWINDOW style used by most frame windows. Creating a window without a title bar is as simple as omitting WS_CAPTION from the window style. It follows that you can remove a title bar from a window that already exists by stripping the WS_CAPTION bit. MFC's CWnd :: ModifyStyle function changes a window's style with one simple function call. When Remove / Restore title is selected from Clock's system menu, CMainWindow :: OnSysCommand toggles the value stored in CMainWindow :: m_bFullWindow from 0 to 1 or 1 to 0 and then calls CMainWindow :: SetTitleBarState, which adds or removes the WS_CAPTION style based on the current value of m_bFullWindow: IF (m_bfulwindow) {
ModifyStyle (WS_CAPTION, 0);
Pmenu-> modifymenu (idm_sysmenu_full_window, mf_string,
IDM_SYSMENU_FULL_WINDOW, _T ("Restore & Title");
}
Else {
ModifyStyle (0, WS_CAPTION);
Pmenu-> modifymenu (idm_sysmenu_full_window, mf_string,
IDM_SYSMENU_FULL_WINDOW, _T ("Remove & Title");
}
The first parameter passed to ModifyStyle specifies the style or styles to remove, and the second parameter specifies the style or styles to add SetTitleBarState also sets the menu item text to match the state of the style bit:. "Remove Title" if the title bar IS Displayed and "Restore Title" if it isn't.
. Toggling WS_CAPTION on and off is only half the battle, however The trick is getting the window's nonclient area to repaint once the window style is changed Calling CWnd :: Invalidate will not do it, but calling SetWindowPos with a SWP_DRAWFRAME parameter will.: SetWindowPos (NULL, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE |
SWP_NOZORDER | SWP_DRAWFRAME);
The combination of SetWindowPos and SWP_DRAWFRAME causes the entire window, including the title bar, to redraw. The other SWP flags passed to SetWindowPos preserve the window's position, size, and position in the z-order-the front-to-back ordering of windows That Determines Which Windows Are Painted On Top of Others.
Implementing Client-Area Drag
One problem with a window without a title bar is that it can not be repositioned with the mouse. Windows are dragged by their title bars, and when there's no title bar, the user has nothing to grab onto. Clock solves this little dilemma by Playing a trick with the window's wm_nchittess handler so what the window can be used by ITS Client Area, a Feature Windows Program WINDLLETURE WINDOWS PROGRAG.
In Windows, every mouse message is preceded by a WM_NCHITTEST message containing screen coordinates identifying the cursor location. The message is normally handled by :: DefWindowProc, which returns a code that tells Windows what part of the window the cursor is over. Windows uses the return value to decide what type of mouse message to send. For example, if the left mouse button is clicked over the window's title bar, :: DefWindowProc's WM_NCHITTEST handler returns HTCAPTION and Windows sends the window a WM_NCLBUTTONDOWN message. If :: DefWindowProc returns HTCLIENT instead, Windows converts the cursor coordinates from screen coordinates to client coordinates and passes them to the window in a WM_LBUTTONDOWN message.The fact that an application sees mouse messages in raw form makes for some interesting possibilities. The following OnNcHitTest handler implements client-area drag By Fooling Windows Into Thinking That The Mouse Is Over The Title Bar When in Fact It's over The Window's CLI ENT Area:
Uint CMainWindow :: Onnchittest (cpoint point)
{
Uint nhittest = cframeWnd :: ONNCHITTEST (POINT);
IF (nhittest == htclient)
NHITTEST = HTCAPTION;
Return nhittest;
}
With this OnNcHitTest handler in place, a window is as easily dragged by its client area as by its title bar And it works even if the window does not have a title bar Try it:.. Click the left mouse button in Clock's client area And Move The Mouse with the button held down. The window of the mouse goes.
Clock uses an OnNcHitTest handler similar to the one shown above. The only difference is that Clock verifies that the left mouse button is down before replacing an HTCLIENT return code with HTCAPTION so that other mouse messages-particularly right-button mouse messages that precede WM_CONTEXTMENU messages -Will Get Through unscathed: uint cmainwindow :: Onnchittest (cpoint point)
{
Uint nhittest = cframeWnd :: ONNCHITTEST (POINT);
IF ((nhittest == htclient) &&
(:: getasynckeystate (mk_lbutton) <0))))
NHITTEST = HTCAPTION;
Return nhittest;
}
............... ..
Using the system menu as a context menu
Removing a window's title bar has other implications, too. Without a title bar, the user has nothing to click on to display the system menu so that the title bar can be restored. Clock's solution is an OnContextMenu handler that displays the system menu as a context menu when the right mouse button is clicked in the window's client area. Popping up a system menu at an arbitrary location is easier said than done because there's no convenient API function for displaying a system menu programmatically. Clock demonstrates one technique that you can use To do it yourself.
When Clock's client area is clicked with the right mouse button, CMainWindow's OnContextMenu handler retrieves a CMenu pointer to the system menu with GetSystemMenu and displays the menu with CMenu :: TrackPopupMenu:
CMenu * pmenu = getSystemMenu (false);
INT NID = (int) pMenu-> TRACKPOPUPMENU (TPM_LEFTALIGN |
TPM_LEFTBUTTON | TPM_RightButton | TPM_RETURNCMD, POINT.X,
Point.y, this);
One problem with this solution is that commands selected from the menu produce WM_COMMAND messages instead of WM_SYSCOMMAND messages. To compensate, Clock passes TrackPopupMenu a TPM_RETURNCMD flag instructing it to return the ID of the selected menu item. If TrackPopupMenu returns a positive, nonzero value, Indicating That An Item Was Selected, Clock Sends Itself A WM_SYSCommand Message with WParam Equal To The Menu Item ID SHOWN BELOW.IF (NID> 0)
SendMessage (WM_SYSCOMMAND, NID, 0);
Consequently, OnSysCommand gets called to process selections from the pseudo_system menu just as it does for selections from the real system menu. To prevent the framework from disabling the items added to the system menu because of the lack of ON_COMMAND handlers, CMainWindow's constructor sets m_bAutoMenuEnable to FALSE. Normally, the framework's automatic enabling and disabling of menu items does not affect items added to the system menu, but Clock's system menu is an exception because it's treated as a conventional menu when it's displayed with TrackPopupMenu.
So far, so good. There's just one problem remaining. Windows interactively enables and disables certain commands in the system menu so that the selection of commands available is consistent with the window state. For example, the Move, Size, and Maximize commands are grayed in a maximized window's system menu but the Restore and Minimize commands are not. If the same window is restored to its unmaximized size, Restore is grayed out but all other commands are enabled. Unfortunately, when you get a menu pointer with GetSystemMenu, the menu items have not been updated yet. Therefore, OnContextMenu calls a CMainWindow function named UpdateSystemMenu to manually update the menu item states based on the current state of the window. After UpdateSystemMenu updates the system menu by placing a series of calls to CMenu :: GetMenuString And cmenu :: ModifyMenu, IT Uses the :: setmenudefaultimem api function to set the default menu item (the one disprayed in boldface type) to Either Restore or Maximize, depending on the window state. UpdateSystemMenu is hardly an ideal solution, but it works, and to date I have not found a better way to keep the items in a programmatically displayed system menu in sync with the window the menu belongs to.Topmost Windows
One of the innovations Windows 3.1 introduced was the notion of a topmost window-a window whose position in the z-order is implicitly higher than those of conventional, or nontopmost, windows. Normally, the window at the top of the z-order is painted on top of other windows, the window that's second in the z-order is painted on top of windows other than the first, and so on. A topmost window, however, receives priority over other windows so that it's not obscured even if it's at the bottom of the z-order. It's always visible, even while it's running in the background.The Windows taskbar is the perfect example of a topmost window. By default, the taskbar is designated a topmost window so that it will be drawn on top of other windows. If two (or more) topmost windows are displayed at the same time, the normal rules of z-ordering determine the visibility of each one relative to the other. You should use topmost windows sparingly because if all windows were topmost Windows, A TopMost Windo W Would No longer be Accorded Priority over Other windows.
.. The difference between a topmost window and a nontopmost window is an extended window style bit WS_EX_TOPMOST makes a window a topmost window You can create a topmost frame window by including a WS_EX_TOPMOST flag in the call to Create, like this:
Create (NULL, _T ("MyWindow"), WS_OVERLAPPEDWINDOW, RectDefault,
NULL, NULL, WS_EX_TOPMOST);
The alternative is to add the style bit atte the window is created by calling setwindowpos with a & wndtopmost parameter, as shown here:
SetwindowPOS (& Wndtopmost, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE);
You can convert a topmost window into a nontopmost window by calling SetWindowPos with the first parameter equal to & wndNoTopMost rather than & wndTopMost.Clock uses SetWindowPos to make its window a topmost window when Stay On Top is checked in the system menu and a nontopmost window when Stay On Top is unchecked. The work is done by CMainWindow :: SetTopMostState, which is called by OnSysCommand. When Stay On Top is checked, Clock is visible on the screen at all times, even if it's running in the background and it overlaps the application Running in the foreground.
Making Configuration Settings Persistent
Clock is the first program presented thus far that makes program settings persistent by recording them on disk. The word persistent comes up a lot in discussions of Windows programming. Saying that a piece of information is persistent means that it's preserved across sessions. If you want Clock to run in a tiny window in the lower right corner of your screen, you can size it and position it once and it will automatically come back up in the same size and position the next time it's started. For users who like to arrange their desktops a certain way, little touches like this one make the difference between a good application and a great one. Other Clock configuration settings are preserved, too, including the title bar and stay-on-top states.
The key to preserving configuration information across sessions is to store it on the hard disk so that it can be read back again the next time the application is started. In 16-bit Windows, applications commonly use :: WriteProfileString, :: GetProfileString, and other API functions to store configuration settings in Win.ini or private INI files. in 32-bit Windows, INI files are still supported for backward compatibility, but programmers are discouraged from using them. 32-bit applications should store configuration settings in the registry instead.The registry is a binary database that serves as a central data repository for the operating system and the applications it hosts. Information stored in the registry is organized hierarchically using a system of keys and subkeys, which are analogous to directories and subdirectories on a Hard Disk. Keys CAN Contain Data Entries Just As Directories CAN Contain Files. Data Entries Have Names and Can Be Assigned Text OR Binary Values. The Upperm ost level in the registry's hierarchy is a set of six root keys named HKEY_CLASSES_ROOT, HKEY_USERS, HKEY_CURRENT_USER, HKEY_LOCAL_MACHINE, HKEY_CURRENT_CONFIG, and HKEY_DYN_DATA. Per Microsoft's recommendations, Windows applications should store private configuration settings under the key
HKEY_CURRENT_USER / SOFTWARE / COMPANYNAME / PRODUCTNAME / VERSION
where CompanyName is the company name, ProductName is the product name, and Version is the product's version number. A registry entry that records the user-selectable window background color for version 2.0 of a product named WidgetMaster from WinWidgets, Inc., might look like THIS:
HKEY_CURRENT_USER / Software / WinWidgets, Inc./WidgetMaster/Version 2.0 / bkgndcolor = 4
Because the information is stored under HKEY_CURRENT_USER, it is maintained on a per-user basis. That is, if another user logs in and runs the same application but selects a different background color, a separate BkgndColor value will be recorded for that user.The win32 API includes an assortment of functions for reading and writing to the registry, but MFC provides a layer on top of the API that makes reading and writing application-specific registry values no different from using ordinary INI files. A call to CWinApp :: SetRegistryKey with the name of a registry key directs the framework to use the registry instead of an INI file. The key name passed to SetRegistryKey corresponds to the company name-for example, "WinWidgets, Inc." in the example above. String and numeric values Are Written to the Registry with Written's WriteProfileString and WriteProfileint Functions and Read Back Back Back with getprofilestring and getprofileint. in an application named myword.exe, The Statements
SetRegistryKey (_T ("wordsmith"));
Writeprofileint (_T ("Version 1.0"), _T ("MRULENGTH"), 8);
Create The Following Numeric Registry Entry:
HKEY_CURRENT_USER / SOFTWARE / WORDSMITH / MYWORD / VERSION 1.0 / MRULENGTH = 8
The Statement
M_nmrulength = getprofileint (_T ("Version 1.0"), _T ("MRULENGTH"), 4);
Reads it back and returns 4 if the entry doesn't exist. Note That MFC generates the product name for you by stripping the .exe extension from the executable file name.
Before IT Terminates, Clock Records The Following Configuration Settings in The Registry:
The value of CMainWindow :: m_bFullWindow, which indicates whether the title bar is displayed The value of CMainWindow :: m_bStayOnTop, which indicates whether Stay On Top is selected The size and position of the frame windowThe next time it starts up, Clock reads the settings back. The full complement of entries that Clock stores in the registry is shown in Figure 14-4. The CMainWindow functions SaveWindowState and RestoreWindowState do the reading and writing. SaveWindowState is called from the window's OnClose and OnEndSession handlers, which are called just before the application closes and just before Windows shuts down, respectively. If Windows is shut down, a running application does not receive a WM_CLOSE message, but it does receive a WM_ENDSESSION message. If you want to know whether Windows is preparing to shut down, simply Add an on_WM_ENDSession Entry to the main window's message map and write an onendsession handler to go with it. The beding parameter passed to Oneendsessi on indicates whether Windows is in fact shutting down A nonzero value means it is;. 0 means Windows was about to shut down but another application vetoed the operation A WM_ENDSESSION message is preceded by a WM_QUERYENDSESSION message, in which each application is given a chance. TO SAY YES or no to an impending shutdown.
Figure 14-4. Clock's Registry Entries As Seen In Registry Editor (regedit.exe).
Clock's title bar and stay-on-top settings are saved to the HKEY_CURRENT_USER / Software / Programming Windows with MFC / CLOCK / Version 1.0 branch of the registry with the following statements in SaveWindowState.
CSTRING VERSION = _T ("Version 1.0");
Myapp.writeprofileint (Version, _T ("fullwindow"), m_bfullwindow; myapp.writeprofileint (Version, _T ("stayontop"), m_bstayontop);
The Settings Are Read Back and Applied to The Window In RestoreWindowState:
CSTRING VERSION = _T ("Version 1.0");
m_bfulwindow = myapp.getprofileint (Version, _T ("fullwindow"), 0);
Settitlebarstate ();
m_bstayontop = myapp.getprofileint (Version, _t ("stayontop"), 0);
SettopmostState ();
RestoreWindowState Is Called by CMYAPP :: InitInstance Right After the Window Is Created But Before It's Displayed on The Screen.
Saving and restoring the window's size and position is a little trickier. If you've never written an application with a window that remembers its size and position, you might think it would be a simple matter of saving the coordinates returned by CWnd :: GetWindowRect so that they can be passed to Create or CreateEx. But there's more to it than that. If you fail to take into account the window's current state (minimized, maximized, or neither minimized nor maximized), all kinds of bad things can happen. for example, if you pass the coordinates of a maximized window to Create or CreateEx, the resultant window will occupy the full extent of the screen but its title bar will have a maximize box instead of a restore box. A persistent window that's closed while it's MINIMIZED or Maximized Should Come Back Up in The Minimized Or Maximized State, And It Should Also Remember ITS Normal Size So That Restoring It Will Restore ITS former size.
The key to preserving a window's size and position and taking relevant state information into account lies in a pair of CWnd functions named GetWindowPlacement and SetWindowPlacement Each accepts the address of a WINDOWPLACEMENT structure, which is defined as follows:. Typedef struct tagWINDOWPLACEMENT {
Uint Length;
Uint flags;
Uint showcmd;
Point PtminPosition;
Point ptmaxposition;
Rect rcNORMALPSITION;
WINDOWPLACEMENT;
WINDOWPLACEMENT brings together in one place everything Windows needs to know to characterize a window's screen state. Length specifies the size of the WINDOWPLACEMENT structure. Both CWnd :: GetWindowPlacement and CWnd :: SetWindowPlacement fill in this field for you. Flags contains zero or more bit flags specifying information about minimized windows. The WPF_RESTORETOMAXIMIZED flag, if present, indicates that a minimized window will be maximized when it is restored. showCmd specifies the window's current display state. It is set to SW_SHOWMINIMIZED if the window is minimized, SW_SHOWMAXIMIZED if the window . is maximized, or SW_SHOWNORMAL if the window is neither minimized nor maximized ptMinPosition and ptMaxPosition hold the screen coordinates of the window's upper left corner when it is minimized and maximized, respectively (Do not rely on ptMinPosition to tell you anything;. in current Versions of Windows, PTMINPSITION IS Set To (3000, 3000) WHEN A Window Is Minimized.) RcNORMALPOSITI on contains the screen coordinates of the window's "normal," or unminimized and unmaximized, screen position. When a window is minimized or maximized, rcNormalPosition specifies the position and size the window will be restored to-provided, of course, that the WPF_RESTORETOMAXIMIZED flag IsoN't set to force a resting window to full screen.
You can preserve a window's screen state across sessions by saving the flags, showCmd, and rcNormalPosition values in the window's WINDOWPLACEMENT structure and restoring these values when the window is re-created. You do not need to save ptMinPosition and ptMaxPosition because Windows fills in their values when the window is minimized or maximized. Clock's SaveWindowState function uses GetWindowPlacement to initialize a WINDOWPLACEMENT structure and then writes the pertinent members of that structure to the registry. The window state is restored when CMyApp :: InitInstance calls CMainWindow :: RestoreWindowState, which in turn calls GetWindowPlacement to fill in a WINDOWPLACEMENT structure; reads the flags, showCmd, and rcNormalPosition values from the registry; copies them to the structure;. and calls SetWindowPlacement The SW_SHOWMINIMIZED, SW_SHOWMAXIMIZED, or SW_SHOWNORMAL parameter passed to SetWindowPlacement in showCmd makes the window Visible, So There's no need to call showwindow if RestoreWindowState returns TRUE, indicating that the window state was successfully restored. In fact, you should skip the usual call placed to ShowWindow from InitInstance if RestoreWindowState returns TRUE because the application object's m_nCmdShow parameter might alter the window's state. Clock's InitInstance function looks like this : Bool cmyapp :: initInstance ()
{
SetRegistryKey (_T ("Programming Windows With MFC");
m_pmainwnd = new cmainwindow;
IF (! (cmainwindow *) m_pmainwnd) -> restoreWindowState ())
m_pmainwnd-> showwindow (m_ncmdshow);
m_pmainwnd-> UpdateWindow ();
Return True;
}
The first time Clock is executed, ShowWindow is called in the normal way because RestoreWindowState returns FALSE. In subsequent invocations, the window's size, position, and visibility state are set by RestoreWindowState, and ShowWindow is skipped.Before calling SetWindowPlacement to apply the state values retrieved from the registry, RestoreWindowState ensures that a window positioned near the edge of a 1,024-by-768 screen will not disappear if Windows is restarted in 640-by-480 or 800-by-600 mode by comparing the window's normal position with The Screen Extents:
wp.rcnorMalPosition.Left = min (wp.rcnormalposition.left,
:: getSystemMetrics - -
:: GetSystemMetrics (SM_CXICON));
wp.rcnormalPosition.top = min (wp.rcnormalposition.top,
:: GetSystemMetrics (SM_CYSCREEN) -
:: getSystemMetrics (SM_CYICON));
Called with SM_CXSCREEN and SM_CYSCREEN parameters, :: GetSystemMetrics returns the screen's width and height, respectively, in pixels. If the window coordinates retrieved from the registry are 700 and 600 and Windows is running at a resolution of 640 by 480, this simple procedure transforms the 700 and 600 into 640 and 480 minus the width and height of an icon. Rather than appear out of sight off the screen and probably leave the user wondering why the application did not start, the window will appear just inside the lower right corner Of the screen.
A good way to test a program that preserves a window's position and size is to resize the window to some arbitrary size, maximize it, minimize it, and then close the application with the window minimized. When the program is restarted, the window should come up minimized, and clicking the minimized window's icon in the taskbar should remaximize it. clicking the restore button should restore the window's original size and position. Try this procedure with Clock, and you should find that it passes the test with flying colors.Controlling the Window size: The WM_GETMINMAXINFO MESSAGE
A final aspect of Clock that deserves scrutiny is its OnGetMinMaxInfo handler. As a window is being resized, it receives a series of WM_GETMINMAXINFO messages with lParam pointing to a MINMAXINFO structure containing information about the window's minimum and maximum "tracking" sizes. You can limit a window's minimum and maximum sizes programmatically by processing WM_GETMINMAXINFO messages and copying the minimum width and height to the x and y members of the structure's ptMinTrackSize field and the maximum width and height to the x and y members of the ptMaxTrackSize field. Clock prevents its window From Being Reduced to Less Than 120 Pixels Horizontally and Vertical Free with The Following OngetminMaxInfo Handler:
Void CMainWindow :: ONGETMINMAXINFO (MinMaxInfo * PMMI)
{
PMMI-> ptmintracksize.x = 120;
PMMI-> ptmintracksize.y = 120;
}
The tracking dimensions copied to MINMAXINFO are measured in device units, or pixels. In this example, the window's maximum size is unconstrained because pMMI-> ptMaxTrackSize is left unchanged. You could limit the maximum window size to one-half the screen size by adding The StatementSpmmi-> PTMaxTracksize.x = :: getSystemMetrics (SM_CXSCREEN) / 2;
PMMI-> PTMaxTracksize.y = :: getSystemMetrics (SM_CYSCREEN) / 2;
To the message handler.