1、在对话框中添加Edit控件
2、在初始化对话框中添加代码如下:
//从文件中读取value
CString SName,filePath;
filePath = GetModuleDir(); //获取文件路径
filePath += "\\config.ini";
LPWSTR lpstr = (LPWSTR)(LPCWSTR)SName; //将CString 转换成LPWSTR
//获取字符串
GetPrivateProfileString(_T("Serial"),_T("Port"),_T(""),lpstr,20,filePath);
//((CEdit *)GetDlgItem(IDC_EDIT1))->SetWindowText(SName);
//获取数字
UINT baudRate = GetPrivateProfileInt(_T("Serial"),_T("BaudRate"),0,filePath);
CString temp;
temp.Format(_T("%d"),baudRate);
//temp = temp + SName ; //注意,转化的cString 不能用“+”重载
((CEdit *)GetDlgItem(IDC_EDIT1))->SetWindowText(temp);
其中GetModuleDir方法如下:
CString CIniFileDlg:: GetModuleDir()
{
HMODULE module = GetModuleHandle(0);
TCHAR pFileName[100];
GetModuleFileName(module, pFileName, 100);
CString csFullPath(pFileName);
int nPos = csFullPath.ReverseFind( _T('\\') );
if( nPos < 0 )
return CString("");
else
return csFullPath.Left( nPos );
}
3、往ini文件中写value
添加一个button控件,并双击添加响应单击事件并在相应函数中添加如下代码:
CString temp,filePath;
filePath = GetModuleDir();
filePath += "\\config.ini";
((CEdit *)GetDlgItem(IDC_EDIT1))->GetWindowText(temp);
WritePrivateProfileString(_T("Serial"),_T("BaudRate"),temp,filePath);
((CEdit *)GetDlgItem(IDC_EDIT2))->GetWindowText(temp);
WritePrivateProfileString(_T("Serial"),_T("Port"),temp,filePath);