MFC使用配置文件

配置文件的一般扩展名是".ini",用于保存用户对软件的个性化配置.配置文件可以使用程序读写,也可以使用记事本直接编辑,可以使用系统生成的:C:\Windows目录下程序同名ini文件,也可以使用用户自己建立的ini文件,还可以写入到注册表中.下面通过案例,一一介绍.

本案例演示通过配置文件,保存程序退出时的屏幕位置,窗口大小,以及标题.当程序再次启动时,这些属性会恢复关闭时的状态.

建立MFC工程,基于对话框,IniFileTest.

 

属性使用多字节字符编码.

使用类向导,建立销毁窗口的处理函数:

void CIniFileTestDlg::OnDestroy()
{
	CDialogEx::OnDestroy();

	// TODO: 在此处添加消息处理程序代码

	//获得窗口退出位置
	CRect window_pos_rect;
	GetWindowRect(window_pos_rect);

	CWinApp* p_process_app = AfxGetApp();
	p_process_app->WriteProfileInt("Place", "Left", window_pos_rect.left);
	p_process_app->WriteProfileInt("Place", "Top", window_pos_rect.top);
	p_process_app->WriteProfileInt("Place", "Right", window_pos_rect.right);
	p_process_app->WriteProfileInt("Place", "Bottom", window_pos_rect.bottom);

//获得窗口大小
	CString window_title_str;
	GetWindowText(window_title_str);
	p_process_app->WriteProfileStringA("Window", "Title", window_title_str);
}

使用了CWinApp类的成员函数:

WriteProfileInt,WriteProfileStringA

作用分别是写入整数,字符串.此外,MFC还提供了成员函数WriteProfileBinary,用于无限制格式写入数据.

配置文件的内容类似于JSON格式数据,由类,如:Place,Window,以及键值对组成.

在初始化函数中,设置窗口属性:

BOOL CIniFileTestDlg::OnInitDialog()
{
	... ...


	// TODO: 在此添加额外的初始化代码

	CRect window_pos_rect;
	CWinApp* p_process_app = AfxGetApp();
	window_pos_rect.left = p_process_app->GetProfileInt("Place", "Left", 0);
	window_pos_rect.top = p_process_app->GetProfileInt("Place", "Top", 0);
	window_pos_rect.right = p_process_app->GetProfileInt("Place", "Right", 0);
	window_pos_rect.bottom = p_process_app->GetProfileInt("Place", "Bottom", 0);

	MoveWindow(window_pos_rect);

	CString window_title_str;
	window_title_str = p_process_app->GetProfileStringA("Window", "Title", "");
	SetWindowText(window_title_str);
	
	return TRUE;  // 除非将焦点设置到控件,否则返回 TRUE
}

GetProfileInt或GetProfileStringA作用是获得配置文件的数据,同样有对应的GetProfileBinary.它们的最后一个参数表示配置项中没有指定项时,函数的返回值.

运行程序,已经可以实现目标效果.

此时,C:\Windows目录下,没有IniFileTest.ini,因为默认配置保存在注册表中,可以运行:

regedit

 

可以发现,注册表中多了一项.

只要将CIniFileTestApp::InitInstance()中的下行代码注释:

SetRegistryKey(_T("应用程序向导生成的本地应用程序"));

即可找到配置文件,在C:\Windows\

 

如果要使用自定义配置文件,可以使用windows api函数.

GetPrivateProfileString,WritePrivateProfileString等.

这些API比之前的对应增加了一个字符串参数在最后,表示配置文件的路径,用户可以自定义配置文件,并选择指定的路径保存.

猜你喜欢

转载自blog.csdn.net/csm1972385274/article/details/80137372