1
我想知道如何將應用程序中的設置保存在C++ builder中的xml或ini文件中。知道Visual Studio在「設置」中有這些功能,我在C++ builder中搜索相同的功能。C++構建器應用程序設置?
用什麼方法來解決這個問題。
我想知道如何將應用程序中的設置保存在C++ builder中的xml或ini文件中。知道Visual Studio在「設置」中有這些功能,我在C++ builder中搜索相同的功能。C++構建器應用程序設置?
用什麼方法來解決這個問題。
使用C++ Builder創建VCL應用程序時,可以使用ini文件保存下次啓動應用程序時想要恢復的設置和值。
首先,包含IniFiles.hpp標題。
#include <IniFiles.hpp>
要保存設置和值,請創建一個新的TIniFile並在OnClose事件中寫入它。
void __fastcall TForm1::FormClose(TObject *Sender, TCloseAction &Action)
{
bool booleanValueToSave = true;
int integerValueToSave = 42;
TIniFile *ini = new TIniFile(ChangeFileExt(Application->ExeName, ".ini"));
ini->WriteString("SectionName", "KeyName", "Value to save as KeyName");
ini->WriteBool("SectionName", "AnotherKeyName", booleanValueToSave);
ini->WriteInteger("SectionName", "YetAnotherKeyName", integerValueToSave);
// To save something like the window size and position
ini->WriteInteger("Settings", "WindowState", Form1->WindowState);
if (Form1->WindowState == wsNormal)
{
ini->WriteInteger("Settings", "MainFrm Top", Form1->Top);
ini->WriteInteger("Settings", "MainFrm Left", Form1->Left);
ini->WriteInteger("Settings", "MainFrm Height", Form1->Height);
ini->WriteInteger("Settings", "MainFrm Width", Form1->Width);
}
delete ini;
}
不要忘記刪除!
那裏的代碼會創建一個與您的可執行文件同名但帶有.ini擴展名的ini文件。將有兩個標題,「SectionName」和「設置」。在標題下您將看到鍵值對,例如「AnotherKeyName = true」和「YetAnotherKeyName = 42」。
然後,要在應用程序啓動時恢復值,請創建一個新的TIniFile並在OnCreate事件中讀取它。
void __fastcall TForm1::FormCreate(TObject *Sender)
{
TWindowState ws;
int integerValueToRestore;
bool booleanValueToRestore;
int someDefaultIntegerValueIfTheKeyDoesntExist = 7;
bool someDefaultBooleanValueIfTheKeyDoesntExist = false;
TIniFile *ini = new TIniFile(ChangeFileExt(Application->ExeName, ".ini"));
integerValueToRestore = ini->ReadInteger("SectionName", "YetAnotherKeyName", someDefaultIntegerValueIfTheKeyDoesntExist);
booleanValueToRestore = ini->ReadBool("SectionName", "AnotherKeyName", someDefaultBooleanValueIfTheKeyDoesntExist);
// To restore the window size and position you saved on FormClose
ws = (TWindowState)ini->ReadInteger("Settings", "WindowState", wsNormal);
if (ws == wsMinimized)
ws = wsNormal;
if (ws == wsNormal)
{
Form1->Top = ini->ReadInteger("Settings", "MainFrm Top", 10);
Form1->Left = ini->ReadInteger("Settings", "MainFrm Left", 10);
Form1->Height = ini->ReadInteger("Settings", "MainFrm Height", 730);
Form1->Width = ini->ReadInteger("Settings", "MainFrm Width", 1028);
}
Form1->WindowState = ws;
delete ini;
}
希望有幫助。