該例是個小練習,有兩個listbox控件,可以通過其中的四個button按鈕,實現從一個listbox向另一個listbox中傳遞數據,操作過程如下:
1、創建一個Dialog based MFC應用程序,命名爲try。
2、爲對話框添加兩個LsitBox控件,分別命名爲IDC_LIST1和IDC_LIST2
3、打開ClassWizard,分別爲IDC_LIST1和IDC_LIST2添加CListBox類型的變量m_list1和m_list2與之相關聯
4、再爲對話框添加四個Button控件,分別命名爲IDC_TO_RIGHT、IDC_TO_LEFT、IDC_RIGHT_ALL、IDC_LEFT_ALL
5、再次打開ClassWizard,爲剛纔添加的button控件添加消息響應函數。響應BN_CLICK消息,消息響應接受默認選項目,分別爲:void CTryDlg::OnToRight()、void CTryDlg::OnToLeft()、void CTryDlg::OnRightAll()、void CTryDlg::OnLeftAll()
6、選擇IDC_LIST1控件,選擇"屬性"->Styles->Selections->Extended,對IDC_LIST2採取同樣的操作
7、對OnToLeft添加如下代碼
void CTryDlg::OnToLeft()
{
// TODO: Add your control notification handler code here
if(m_list2.GetCount()==0)
{
MessageBox("list2 is empty!");
return;
}
int buf[10];
CString str;
int number = m_list2.GetSelItems(MAX_NUM,buf);
for(int i=0;i<number;i++)
{
m_list2.GetText(buf[i],str);
m_list1.AddString(str);
}
for(i=0;i<number;i++)
{
m_list2.DeleteString(buf[i]-i);
}
}
8、對OnToRight添加如下代碼
void CTryDlg::OnToRight()
{
// TODO: Add your control notification handler code here
if(m_list1.GetCount()==0)
{
MessageBox("list1 is empty!");
return;
}
int buf[10];
CString str;
int number = m_list1.GetSelItems(MAX_NUM,buf);
for(int i=0;i<number;i++)
{
m_list1.GetText(buf[i],str);
m_list2.AddString(str);
}
for(i=0;i<number;i++)
{
m_list1.DeleteString(buf[i]-i);
}
}
9、對OnRightAllt添加如下代碼
void CTryDlg::OnRightAll()
{
// TODO: Add your control notification handler code here
if(m_list1.GetCount()==0)
{
MessageBox("list1 is empty");
return;
}
CString str;
for(int i=0;i<m_list1.GetCount();i++)
{
m_list1.GetText(i,str);
m_list2.AddString(str);
}
for(i=0;i<m_list1.GetCount();)
{
m_list1.DeleteString(i);
}
}
10、對OnLeftAllt添加如下代碼
void CTryDlg::OnLeftAll()
{
// TODO: Add your control notification handler code here
if(m_list2.GetCount()==0)
{
MessageBox("list2 is empty");
return;
}
CString str;
for(int i=0;i<m_list2.GetCount();i++)
{
m_list2.GetText(i,str);
m_list1.AddString(str);
}
for(i=0;i<m_list2.GetCount();)
{
m_list2.DeleteString(i);
}
}
11、最後,在OnInitUpdate函數中,添加
CString str;
for(int i=0;i<10;i++)
{
str.Format("%d",i);
m_list1.AddString(str);
}
爲list1添加了10條記錄
12、現在運行下程序,看看效果吧:)