"Go" VS2010/MFC Programming Primer 25 (Common Controls: Combo box controls combo boxes)

Source: Internet
Author: User

Original URL: http://www.jizhuomi.com/software/189.html

A chicken peck of rice Speaking of the use of ListBox control, this section mainly explains the combo box control combo box. Combo boxes are also quite common, for example, when you set a language or location on a Windows system control Panel, there are many options for selecting the control that is the combo box control. It provides a lot of convenience for our daily operation.


Introduction to Combo box controls

The combo box is actually a combination of an edit box and a list box, divided into three types: simple combo box, drop-down (Dropdown) combo box and drop-down list combo box. Let's talk about their differences.

The list box in the simple combo box is always displayed.

The dropdown combo box does not display the list box by default, only the drop-down arrow to the right of the edit box pops up the list box.

The edit box for a drop-down list combo box is not editable, and the text is displayed in the edit box only after the user selects an item in the drop-down list box. 


After the above introduction, you should know, the most commonly used when the subordinate pull-type combo box and drop-down list combo box, they can in many cases make the program look more professional, more concise, so that the user in the choice of operation more convenient.


When the combo box is manipulated, a notification message is sent to the parent window, and the notification messages and their meanings are as follows:

       cbn_closeup: The list box component of a combo box is closed, and a simple combo box does not send the notification message
        CBN_DBLCLK: The user double-clicks on a list item, only the simple combo box will send the notification message
       Cbn_ DROPDOWN: Combo box list box component drop-down, simple combo box does not send the notification message
       Cbn_ Editupdate: The message is sent when the edit box is ready to display the changed body, and the drop-down list combo box does not send the message
       cbn_ Editchange: The content of the edit box is changed by the user, and unlike cbn_editupdate, the message is emitted after the body of the edit box is refreshed, and the drop-down list combo box does not send the message
        cbn_errspace: Combo box cannot request enough memory to hold list items
       cbn_ Selendcancel: Indicates that the user's selection should be canceled, causing the message to be sent
       cbn_ when the user selects an item in the list box and then clicks the mouse outside the combo box control Selendok: The user selects an item and then presses the ENTER key or clicks the scroll down arrow, which indicates that the user confirmed their choice
       cbn_ Killfocus: Combo box loses input focus
       Cbn_selchange: The user changes the selection of the list by clicking or moving the arrow keys
        cbn_setfocus: Combo box gets input focus


Creating a combo box control

MFC encapsulates all the operations of a combo box control into the CComboBox class.

When we add a combo box to a dialog box, we can drag the combo box control into the dialog template and then add the CComboBox type of control variable, but if we want to create it dynamically in the program, we'll use the member function of the CComboBox class create. The prototype of the CREATE function is as follows:

Virtual BOOL Create (

DWORD Dwstyle,
Const rect& RECT,
cwnd* pParentWnd,
UINT NID
);


As you can see, the Create member function of the CComboBox class is very similar to the Create member function of the preceding control classes, dwstyle specifies the style of the combo box control, Rect is the position and size of the combo box when the list box pops up, pParentWnd is a pointer to the parent window , the ID of the combo box control cannot be specified for Null,nid. Finally, we will focus on the dwstyle parameters. The style of the combo box control includes the following, and gives the corresponding description:


Cbs_autohscroll: Style that makes the edit box component scroll horizontally
Cbs_disablenoscroll: Causes the list box to display a forbidden vertical scrollbar when scrolling is not required
Cbs_dropdown: Specify a drop-down combo box
Cbs_dropdownlist: Specify a drop-down list combo box
Cbs_hasstrings: Specifies a self-drawn combo box with a string
Cbs_lowercase: Automatically converts all text in the Edit box and list box to lowercase characters
Cbs_nointegralheight: The size of a combo box is specified by the application instead of Windows, and typically the size specified by Windows hides parts of the list item.
Cbs_oemconvert: Enables the body of the edit box component to convert from one to the other between the ANSI character set and the OEM character set. This is useful when you include a file name in the edit box
Cbs_ownerdrawfixed: Specifies a custom combo box, that is, the parent window is responsible for drawing the contents of the list box, and the list items have the same height
Cbs_ownerdrawvariable: Specifies a custom combo box, and the list item has a different height
Cbs_siimple: Specify a simple combo box
Cbs_sort: Automatically sort items in a list box component
Cbs_uppercase: Automatically converts all text in the Edit box and list box to uppercase characters


The dwstyle parameter can be a combination of the above styles. As with other controls, styles such as Ws_child, Ws_visible, Ws_tabstop, and Ws_vscroll are also typically specified when created.


When you add a combo box control directly in a dialog box template, the properties in its property page contain the above style, such as the property uppercase is set to True to specify the Cbs_uppercase style.


main member functions of the CComboBox class

because combo boxes are composed of edit boxes and list boxes, there are many similarities between the action of a combo box and the action of the edit box and the list box, and similarly, the member function of the CComboBox class has a lot in common with the member functions of the CEdit class and the CListBox class. Not only are functions similar, even function names and parameters are similar. Chicken Peck Rice The following is probably the main member function of the CComboBox class, and more detailed information can be found in MSDN.


int GetCount () const;
Gets the number of list items in the list box for the combo box control.


int GetCurSel () const;
Gets the index of the selected item in the ListBox control's list box, or returns CB_ERR if no item is selected.


int SetCurSel (int nselect);
Select an item in the list box of the combo box control. The Nselect parameter specifies the index of the list item to select, and if 1 the current selection in the list box is unchecked and the edit box is emptied.


DWORD Geteditsel () const;
Gets the position of the start and end characters of the current selection in the edit box of the combo box control. The function returns a 32-digit number, a low 16-bit starting position, and a high 16-bit position of the first non-selectable character after the selection range. If the function is used in a drop-down list combo box, Cb_err is returned.


BOOL seteditsel (int nstartchar,int nendchar);
Used to select characters in the edit box of a combo box control. The nStartChar parameter specifies the starting position, and the nEndChar parameter specifies the terminating position.


dword_ptr getitemdata (int nIndex) const;
Gets the 32-bit data that is associated with the specified item in the combo box. The nindex parameter specifies the index of an item of the combo box control's list box (starting at 0).


int setitemdata (int nindex,dword_ptr dwitemdata);
Sets an associated 32-digit number for a specified combo box list item. The nindex parameter specifies the index of the list item to be set. The Dwitemdata parameter specifies the new value to associate.


void Getlbtext (int nindex,cstring& rString) const;
Gets the string of an item from the list box of a combo box control. The nindex parameter specifies the index of the list item to get the string, and the CString parameter is used to receive the fetched string.


int Getlbtextlen (int nIndex) const;
Gets the string length of an item in the list box of a combo box control. The nindex parameter specifies the index of the list item to get the length of the string.


int gettopindex () const;
Gets the index of the first visible item in the list box of a combo box control.


int settopindex (int nIndex);
Sets a specified item in the list box of a combo box control to be visible. The nindex parameter specifies the index of the list item. The function returns 0 if it succeeds, and returns CB_ERR if an error occurs.


BOOL limittext (int nmaxchars);
Used to limit the maximum length of bytes that a user can enter in the edit box of a combo box control. The Nmaxchars parameter specifies the maximum byte length to which the user can enter text, and if 0, the length is limited to 65,535 bytes.


int addstring (LPCTSTR lpszstring);
Adds a new list item to the list box in the combo box control. The lpszstring parameter is a pointer to the string to be added. If the return value of the function is greater than or equal to 0, then it is the index of the new list item and returns CB_ERR if there is an error, and returns Cb_errspace if there is not enough memory to hold the new string.


int deletestring (UINT nIndex);
Deletes a list item at a specified position in the combo box. The nindex parameter specifies the index of the list item to be deleted. If the return value of the function is greater than or equal to 0, then it is the number of remaining list items in the combo box. Returns CB_ERR if the index specified by nindex exceeds the number of list items.


int FindString (int nstartafter,lpctstr lpszstring) const;
Finds but does not select the first list item that contains the specified prefix in the combo box control's list box. The Nstartafter parameter specifies the index of the list item before the first list item to be looked up. Lpszstring points to the string that contains the prefix to find. If the return value of the function is greater than or equal to 0, then it is the index of the matching list item and returns CB_ERR if the lookup fails.


int insertstring (int nindex,lpctstr lpszstring);
Inserts a list item into the list box of a combo box control. The nindex parameter specifies where to insert the list item, and the lpszstring parameter specifies the string to insert. The function returns the position where the string was inserted, and returns CB_ERR if there is an error, and returns Cb_errspace if there is not enough memory to hold the new string.


int selectstring (int nstartafter,lpctstr lpszstring);
Finds a string in the combo box control's list box, selects it if found, and displays it in the edit box. Parameters are the same as findstring. Returns the index of this list item if the string is found, and returns CB_ERR if the lookup fails, and the current selection does not change.

In addition, the CComboBox class inherits the member functions of the CWnd class GetWindowText, SetWindowText, and so on.


CComboBox Class Application Example

Finally, the chicken peck rice to everyone to write a simple example, explain the ccombobox of several member functions and notification messages, such as the use of methods. This instance implements the ability to display the text of a newly selected list item to the edit box when the combo box contains a list of Web sites that toggles the selection of a list item in the list box of a combo box control. Here are the specific implementation steps:


1. Create a dialog-based MFC project with the name set to "Example25".

2. In the automatically generated dialog template Idd_example25_dialog, delete "Todo:place dialog controls here." The static text control, the OK button, and the Cancel button. Add a COMBO box control with the ID set to the Idc_web_combo,type property set to drop list, a drop-down combo box, the edit box does not allow user input, the Sort property is set to False to cancel the sort display. Add a static text control and an edit box, and the Caption property of the static text control is set to "The Web site you selected:" And the edit box has the ID set to Idc_sel_web_edit,read only property set to True. 

3. Add the CComboBox type control variable m_comboweb for the combo box Idc_web_combo.

4. When the dialog is initialized, we add the site name to the combo box, and the first item is selected by default, then the Cexample25dlg::oninitdialog () function needs to be modified to:


C + + code

  1. BOOL CExample25Dlg::OnInitDialog()   
  2. {   
  3.     CDialogEx::OnInitDialog();   
  4.   
  5.     // Add "About..." menu item to system menu.   
  6.   
  7.     // IDM_ABOUTBOX must be in the system command range.   
  8.     ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX);   
  9.     ASSERT(IDM_ABOUTBOX < 0xF000);   
  10.   
  11.     CMenu* pSysMenu = GetSystemMenu(FALSE);   
  12.     if (pSysMenu != NULL)   
  13.     {   
  14.         BOOL bNameValid;   
  15.         CString strAboutMenu;   
  16.         bNameValid = strAboutMenu.LoadString(IDS_ABOUTBOX);   
  17.         ASSERT(bNameValid);   
  18.         if (!strAboutMenu.IsEmpty())   
  19.         {   
  20.             pSysMenu->AppendMenu(MF_SEPARATOR);   
  21.             pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu);   
  22.         }   
  23.     }   
  24.   
  25.     // Set the icon for this dialog.  The framework does this automatically   
  26.     //  when the application‘s main window is not a dialog   
  27.     SetIcon(m_hIcon, TRUE);         // Set big icon   
  28.     SetIcon(m_hIcon, FALSE);        // Set small icon   
  29.   
  30.     // TODO: Add extra initialization here   
  31.     // Add a list item "Chicken glutinous rice" to the list box of the combo box control
  32.     m_comboWeb.AddString(_T("chicken glutinous rice"));   
  33.     // Add a list item "Baidu" to the list box of the combo box control 
  34.     m_comboWeb.AddString(_T("Baidu"));  
  35.     // Insert the list item "Sina" at the position where the index is 1 in the list box of the combo box control.
  36.     m_comboWeb.InsertString(1, _T("Sina"));   
  37.   
  38.     // Select the first item by default
  39.     m_comboWeb.SetCurSel(0);   
  40.     // The first item of the text "Chicken glutinous rice" is displayed by default in the edit box.   
  41.     SetDlgItemText(IDC_SEL_WEB_EDIT, _T("chicken glutinous rice"));  
  42.   
  43.     return TRUE;  // return TRUE  unless you set the focus to a control   
  44. }  

5. We want to use the CBN_SELCHANGE notification message when the list item selected in the combo box changes to show the latest selection in real time to the edit box. Add the message handler function Cexample25dlg::oncbnselchangewebcombo () to the notification message cbn_selchange for the list box Idc_web_combo, and modify the following:


C + + code


  1. Void CExample25Dlg::OnCbnSelchangeWebCombo()
  2. {
  3. // TODO: Add your control notification handler code here
  4.      CString strWeb;
  5.      Int nSel;
  6.      / / Get the index of the selected item in the list box of the combo box control
  7.      nSel = m_comboWeb.GetCurSel();
  8.      / / Get the string according to the selected index
  9.      m_comboWeb.GetLBText(nSel, strWeb);
  10.      // Display the selected string in the combo box to the IDC_SEL_WEB_EDIT edit box
  11.      SetDlgItemText(IDC_SEL_WEB_EDIT, strWeb);
  12. }

6. Run the program, the Popup Results dialog box, the dialog box in the combo box when you change the selection, the display in the edit box will change accordingly.

These are the contents of the combo box. Compared to the number of CComboBox class member functions, the example of this section only uses a few, you can try the other member functions according to the above. Have questions welcome to the chicken Peck rice to exchange discussions.


 VS2010/MFC Programming Primer 25 (Common Controls: Combo box controls combo boxes)

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.