MFC中CCOMBOX組合框的使用

MFC中CCOMBOX組合框的使用

如何在MFC中使用CCOMBOX組合框?下面將用一個例子介紹CCOMBOX組合框控件常用的方法。

首先我們新建一個single類型的mfc.exe工程,在菜單欄中添加一個菜單項,如“CCOMBOX組合框”,雙擊後

可以在裏面添加相關事件。

插入一個Dialog對話框,並添加一個類CDlgCombox,上面添加2個組合框,7個按鈕。

詳細代碼如下:

// DlgCombox.cpp : implementation file
//

#include "stdafx.h"
#include "testvc.h"
#include "DlgCombox.h"

#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif

/////////////////////////////////////////////////////////////////////////////
// CDlgCombox dialog


CDlgCombox::CDlgCombox(CWnd* pParent /*=NULL*/)
 : CDialog(CDlgCombox::IDD, pParent)
{
 //{{AFX_DATA_INIT(CDlgCombox)
 //}}AFX_DATA_INIT
}


void CDlgCombox::DoDataExchange(CDataExchange* pDX)
{
 CDialog::DoDataExchange(pDX);
 //{{AFX_DATA_MAP(CDlgCombox)
 DDX_Control(pDX, IDC_EDIT1, m_EditName);
 DDX_Control(pDX, IDC_COMBO2, m_ComboxSex);
 DDX_Control(pDX, IDC_COMBO1, m_ComboxName);
 //}}AFX_DATA_MAP
}


BEGIN_MESSAGE_MAP(CDlgCombox, CDialog)
 //{{AFX_MSG_MAP(CDlgCombox)
 ON_BN_CLICKED(IDC_BUTTON1, OnAddString)
 ON_BN_CLICKED(IDC_BUTTON3, OnGetCount)
 ON_BN_CLICKED(IDC_BUTTON4, OnGetWindowText)
 ON_BN_CLICKED(IDC_BTN_CLEAR, OnBtnClear)
 ON_BN_CLICKED(IDC_BTN_CLEAR2, OnBtnClearList)
 ON_BN_CLICKED(IDC_BTN_DELETE, OnBtnDelete)
 //}}AFX_MSG_MAP
END_MESSAGE_MAP()

/////////////////////////////////////////////////////////////////////////////
// CDlgCombox message handlers

void CDlgCombox::OnAddString() //插入或者添加一項
{
 // TODO: Add your control notification handler code here
 CString str;
 m_EditName.GetWindowText(str);
 int i=m_ComboxName.GetCount();
// m_ComboxName.InsertString(i,str );//如果在後面插入,請用
 UpdateData(FALSE);
  m_ComboxName.SetCurSel(0);


}

void CDlgCombox::OnGetCount()  //得到下拉列表中的項目總數
{
 // TODO: Add your control notification handler code here
  CString str;
     int i=m_ComboxName.GetCount();
 
     str.Format ("%d",i);
  str="下拉列表中一共有"+str+"項.";
  AfxMessageBox(str);
}

void CDlgCombox::OnGetWindowText() //得到被選擇的文本
{
 // TODO: Add your control notification handler code here
 CString str;
 m_ComboxName.GetWindowText(str);
    CString strSex;
 m_ComboxSex.GetWindowText(strSex);
 str="您選擇的姓名是"+str+",性別是"+strSex;
    AfxMessageBox(str);
}

void CDlgCombox::OnBtnClear() //清除被選定的文本,此法適合下拉列表中有值
{
 // TODO: Add your control notification handler code here
 m_ComboxName.SetEditSel(0, -1);
 m_ComboxName.Clear() ;
 UpdateData(FALSE);
}

void CDlgCombox::OnBtnClearList() //清除下拉列表
{
 // TODO: Add your control notification handler code here
  
   for (int i=0;i < m_ComboxName.GetCount();i++)
   {
  m_ComboxName.DeleteString( i);
 i--;
   }
 UpdateData(FALSE);
}

void CDlgCombox::OnBtnDelete() //清除被選定的文本
{
 // TODO: Add your control notification handler code here
 CString str;
// m_ComboxName.GetWindowText(str);
  m_ComboxName.SetWindowText("");
    UpdateData(FALSE);
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章