Creating an Up-Down Control

The code on the next page demonstrates how easy it is to create a spin box on the fly as part of a dialog box. You might want to do this if you are using one dialog box for several applications—one instance could show the current value as static information, while another might allow the user to change this data. When the user chooses OK in the dialog box, the program retrieves and saves the selection in the spin box and closes the dialog box. (To use an up-down control in your application, remember to include the COMMCTRL.H header file and to include the COMCTL32.LIB file in your list of libraries.)

BOOL APIENTRY Spin (
HWND hDlg,
UINT message,
UINT wParam,
LONG lParam)
{
static HWND hWndUpDown, hWndBuddy;
BOOL bErr;

switch (message)
{
case WM_INITDIALOG:
// Get a handle to the edit (buddy) control.
hWndBuddy = GetDlgItem (hDlg, IDE_BUDDY);

// Create the up-down control.
hWndUpDown = CreateWindowEx (
0L,
UPDOWN_CLASS,
"",
WS_CHILD | WS_BORDER | WS_VISIBLE | UDS_WRAP | UDS_ARROWKEYS |
UDS_ALIGNRIGHT | UDS_SETBUDDYINT,
0, 0, 8, 8,
hDlg,
(HMENU)ID_UPDOWN,
hInst,
NULL);

// Set the buddy window.
SendMessage (hWndUpDown, UDM_SETBUDDY, (LONG)hWndBuddy, 0L);

// Set the range.
SendMessage (hWndUpDown, UDM_SETRANGE, 0L,
MAKELONG (MAX_SPIN, MIN_SPIN));

// Set the default value in the edit control.
SetDlgItemInt (hDlg, IDE_BUDDY, 1, FALSE);

return TRUE;

case WM_COMMAND:
switch (LOWORD (wParam))
{
case IDOK:
iNumLines = (int) GetDlgItemInt (hDlg, IDE_BUDDY,
&bErr, FALSE);
InvalidateRect (hWndMain, NULL, TRUE);

case IDCANCEL:
EndDialog (hDlg, TRUE);
break;
}
break;

}

return FALSE;
}

If you don't need to create your spin box dynamically, and if you are using Microsoft Visual C++ version 2.1 or later, you can take advantage of the resource editor. The resource editor supports up-down controls, and you can place one of these controls in your dialog box as you would any other control. When I ported the UPDOWN sample to MFC (MFCSPIN), I used the resource editor. I created the CSpin class, derived from CDialog, and set up the m_Lines member variable to hold the number of lines. Here is the terribly complex code required to use the spin box:

// CSpin message handlers

BOOL CSpin::OnInitDialog ()
{
CDialog::OnInitDialog ();

// Set the buddy control.
m_Spin.SetBuddy (GetDlgItem (IDC_LINES));

// Set the range.
m_Spin.SetRange (1, 20);

return TRUE; // return TRUE unless you set the focus to a control
// EXCEPTION: OCX property pages should return FALSE
}

void CFcspinView::OnSpin ()
{
CSpin spinDlg;

if (spinDlg.DoModal() == IDOK)
{
m_NumLines = spinDlg.m_Lines;
GetDocument()->UpdateAllViews (NULL);
}
}

Of course, this wasn't difficult at all. As you can see, it's easy to use the new controls—and even easier to have the resource editor help you out.