Search code examples
windowslazarus

Scan file after start of programm


I've added a TToggleBox in my Lazarus tool and now i want it to be set according to the existence of a string in a file located in the same directory. Therefore i want Lazarus to the check the file for the string right after the programm has started. If it cointains the string (for example "hello world") it should set the Caption of ToggleBox1 (see underneath) to "Activated" and if the string is not present to "Deactivated". How do i do this?

TToggleBox:

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

Also, after the caption togglebox has been set by the tool I want to interact with it furthermore. Meaning, when the string was not found and the Caption of the ToggleBox has been set to "Deactivated", i want to press the ToggleBox to start a cmd-script and set the Caption to "Activated" and reverse (if string found and Caption set to "Activated" by pressing the ToggleBox i want to set the Caption to "Deactivated" and start another cmd script). How can you do this?


Solution

  • You can use a TStringList to load the file from disk, assuming it is a textfile, then use the Pos() function to see if the stringlist's Text property contains the string of interest. For example:

    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;
    

    I assume you can work out how to use this function in your code to achieve the desired result. If not, ask in a comment.