如何在下拉框里显示上几次程序运行的输入信息
一、首先包含使用链表的头文件
#define HIS_LENGTH 10 //保存的最大历史记录数
#define STR_LENGTH 1024 //字符串的最大长度
#include "afxtempl.h" //为了使用链表必须包含的头文件
二、在对话框头文件中定义保存数据的链表和保存文件的路径变量
protected:
CList<CString, CString&>m_HisStrList;
CString m_strFile;
三、构造函数中初始化文件路径
m_strFile = ".\\hr.dat";
四、在对话框的OnInitDialog中读文件并将这些数据显示在CComboBox控件中
CDialog::OnInitDialog();
//打开文件,并将数据读入链表中
CFile file;
if(file.Open(m_strFile,CFile::modeRead))
{
DWORD dwRead = 1;
while(dwRead)
{
char buffer[STR_LENGTH];
dwRead = file.Read(buffer,STR_LENGTH);
if(dwRead)
{
buffer[dwRead] = 0;
CString str;
str.Format("%s",buffer);
m_HisStrList.AddTail(str);
}
}
file.Close();
}
//将链表中的数据放入下拉框中
CComboBox* pBox = (CComboBox*)GetDlgItem(IDC_COMBO1);
POSITION pos = m_HisStrList.GetHeadPosition();
while( pos )
{
CString str = m_HisStrList.GetNext( pos );
pBox->AddString(str);
}
五、给对话框增加Update按钮,当在CComboBox控件中输入字符串后按该按钮将数据记录下来
CComboBox* pBox = (CComboBox*)GetDlgItem(IDC_COMBO1);
CString str = "";
pBox->GetWindowText(str);
//忽略空数据
if( str = = "" )
return;
//判断输入的数据以前是否已经存在
POSITION pos = m_HisStrList.GetHeadPosition();
BOOL bExist = FALSE;
while(!bExist && pos)
{
if( str.CompareNoCase( m_HisStrList.GetNext( pos ) ) == 0)
{
bExist = TRUE;
}
}
//如果是新数据则保存起来,否则不理睬
if( !bExist )
{
m_HisStrList.AddTail( str );
//当数据条数超过规定的HIS_LENGTH时去掉最旧的数据
if( m_HisStrList.GetCount() > HIS_LENGTH )
{
m_HisStrList.RemoveHead();
pBox->DeleteString(pBox->GetCount() -1 );
}
pBox->AddString(str);
}
六、通过类向导响应对话框的WM_DESTROY消息。退出程序时将链表的数据保存到文件中
if( !m_HisStrList.IsEmpty() )
{
CFile file;
if(file.Open(m_strFile,CFile::modeCreate|CFile::modeWrite))
{
POSITION pos = m_HisStrList.GetHeadPosition();
while( pos )
{
char buffer[STR_LENGTH];
CString str = m_HisStrList.GetNext( pos );
int nLen = sprintf(buffer,"%s",str);
buffer[nLen] = 0;
file.Write( buffer,STR_LENGTH );
}
file.Close();
}
}
CDialog::OnDestroy();

浙公网安备 33010602011771号