Visual C++ and MFC Programming 2nd Edition

(Martin Jones) #1

Visual C++ and MFC Fundamentals Chapter 17: Track-Based Controls


Once a spin button is ready to hold values, its default value is the lowest specified with
the SetRange() or the SetRange32() method. For example, if you create a spin button
that can hold values from 15 to 62, when the control displays at startup, it would assume
a value of 15. The value held by a spin button is referred to as its position. If you want the
control to have a value different than the lowest, that is, to hold a different position, call
the CSpinButtonCtrl::SetPos() method. Its syntax:

int SetPos(int nPos);

This method takes as argument the new value of the spin button. The value must be in the
range set with the SetRange() or the SetRange32() methods. Here is an example:

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

// TODO: Add extra initialization here
CSpinButtonCtrl *SpinCtrl = new CSpinButtonCtrl;
CStatic *SpinBuddy;

SpinCtrl->Create(WS_CHILD | WS_VISIBLE | UDS_SETBUDDYINT,
CRect(60, 10, 80, 35), this, 0x128);

SpinCtrl->SetRange(4, 64);
SpinCtrl->SetBase(10);

SpinCtrl->SetPos(36);

SpinBuddy = reinterpret_cast<CStatic *>(GetDlgItem(IDC_SPIN_BUDDY));
SpinCtrl->SetBuddy(SpinBuddy);
SpinBuddy->SetWindowText("4");

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

To explore the spin button, the user click one of its arrow buttons or presses the arrow
keys to increase or decrease the control’s value. The only actual thing the spin button
provides is the value it holds. It is up to you to decide what to do with such a value. This
means that, on a regular basis, you will need to retrieve the current value of the control
and do whatever you want with it.. To get the position of a spin button, call the
CSpinButtonCtrl::GetPos() method. Its syntax is:

int GetPos() const;

This method returns the value of the spin button at the time the method is called.

Practical Learning: Using a Spin Button



  1. If you are using MSVC 6, press Ctrl + W to access the Class Wizard. Click the
    Member Variables property page. Click IDC_SPIN_RED and click Add Variable...
    If you are using MSVC 7, on the dialog box, right-click the most left spin button and
    click Add Variable...

  2. Set the name of the variable to m_SpinRed

Free download pdf