C++ Builder 应用程序设置?

3

我希望了解如何在C++ Builder中将应用程序设置保存到xml或ini文件中的方法。我知道Visual Studio在“设置”中具有这些功能,我正在寻找相同的功能。

请问应该使用哪种方法来解决这个问题呢?

1个回答

3
使用C++ Builder创建VCL应用时,您可以使用ini文件保存您想要在下次启动应用程序时恢复的设置和值。

首先,需要包含IniFiles.hpp头文件。
#include <IniFiles.hpp>

为了保存设置和值,请在OnClose事件中创建一个新的TIniFile并向其中写入。

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"和"Settings"。在标题下面,您将看到键值对,例如"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;
}

希望这有所帮助。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接