简体   繁体   中英

How can I create a Spin Button Control dynamically in MFC using CSpinButtonCtrl class?

I realize that this is a trivial problem and I even looked at an MFC book(Programming Windows with MFC by Prosise). However, I couldn't really find a solution.

I am trying to create a Spin Button Control dynamically and here is a simplified code:

    CEdit* m_editControl = new CEdit();
    m_EditControl->Create(WS_VISIBLE | WS_CHILD , rectEdit, this, EditID);

    CSpinButtonCtrl* m_spinControlCtrl = new CSpinButtonCtrl;
    m_spinControlCtrl->Create(WS_VISIBLE | WS_CHILD, rectSpinButton, this, SpinID);

    m_spinControlCtrl->SetBase(10);
    m_spinControlCtrl->SetBuddy(m_editControl );
    m_spinControlCtrl->SetRange(-55, 55);

My problem is that the spin button does not change the value of the CEdit. Am I missing something? How can I create a Spin Button Control dynamically?

Your spin control is missing the style UDS_SETBUDDYINT :

UDS_SETBUDDYINT Causes the up-down control to set the text of the buddy window (using the WM_SETTEXT message) when the position changes. The text consists of the position formatted as a decimal or hexadecimal string.

I also suggest setting UDS_ARROWKEYS so the arrow keys can be used to increment or decrement the value when the focus is on the edit control.

For the edit control I would add WS_TABSTOP so the user can navigate using the TAB key and WS_EX_CLIENTEDGE so the edit control shows the regular themed border.

I also noticed that you use dynamic memory allocation for the controls, which is not necessary. Just create non-pointer member variables like CEdit m_EditControl; so you don't have to worry about deallocation.

Fixed code:

m_EditControl.CreateEx(WS_EX_CLIENTEDGE, L"Edit", L"0", WS_VISIBLE|WS_CHILD|WS_TABSTOP, 
                       rectEdit, this, EditID);

m_spinControlCtrl.Create(WS_VISIBLE|WS_CHILD|UDS_SETBUDDYINT|UDS_ARROWKEYS, 
                         rectSpinButton, this, SpinID);

m_spinControlCtrl.SetBase(10);
m_spinControlCtrl.SetBuddy(&m_EditControl);
m_spinControlCtrl.SetRange(-55, 55);

I also strongly suggest learning to use Spy++ . This is how I actually arrived at this answer. Using the resource editor I just dropped an edit control and an up-down control onto a dialog and used Spy++ to observe the default window styles.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM