首页 > 解决方案 > 程序启动后扫描文件

问题描述

我在我的 Lazarus 工具中添加了一个 TToggleBox,现在我希望根据位于同一目录中的文件中是否存在字符串来设置它。因此,我希望 Lazarus 在程序启动后立即检查文件中的字符串。如果它包含字符串(例如“hello world”),它应该将 ToggleBox1 的 Caption(见下文)设置为"Activated",如果字符串不存在于"Deactivated". 我该怎么做呢?

切换框:

procedure TForm1.ToggleBox1Change(Sender: TObject);
begin
 if ToggleBox1.Checked then
  begin
     ToggleBox1.Caption:='Deactivated'
   end
   else ToggleBox1.Caption:='Activated';
end; 

此外,在工具设置了标题切换框后,我还想与它进行交互。意思是,当找不到字符串并且 ToggleBox 的 Caption"Deactivated""Activated"设置"Activated"为我想将 Caption 设置为"Deactivated"并启动另一个 cmd 脚本)。你怎么能做到这一点?

标签: windowslazarus

解决方案


您可以使用 TStringList 从磁盘加载文件,假设它是一个文本文件,然后使用 Pos() 函数查看字符串列表的 Text 属性是否包含感兴趣的字符串。例如:

function TextFileContains(cost AFileName, AString : String) : boolean;
var
  StringList : TStringList;
begin
  StringList := TStringList.Create;
  try
    Stringlist.LoadFromFile(AFileName);  //  Note:  AFileName should include the full path to the file
    Result := Pos(AString, StringList.Text) > 0;
  finally
    StringList.Free;
  end;
end;

我假设你可以弄清楚如何在你的代码中使用这个函数来达到预期的结果。如果没有,请在评论中询问。


推荐阅读