I am trying to create a simple chat program by writing to a shared file on my network

Tags: delphi timer
Question!

I am trying to use a timer to check the the timestamp of the file to check if it has been modified, if this is true it must add the line from the text file to a richedit. The problem is that it continually adds the line to the richedit every 1/4 second (timer interval). I have tried different methods but can't get it right.

procedure TForm1.Timer1Timer(Sender: TObject);
Var
Filet : textfile;
filename, readtxt : string;
filedate1, filedate2 : integer;
begin

assignfile(filet, 'S:\share.talk');
filename := 'S:\share.talk';
filedate1 := FileAge(filename);

if filedate1 <> filedate2 then begin
reset(filet);
readln(filet, readtxt);
richedit1.lines.add(readtxt);
closefile(filet);
filedate2 := filedate1;
end;//if
end;

thanks for all help.



Answers

This is because everytime you are resetting the filedate1 and filedate2 when the procedure runs. A better way to implement this function is to return the lastwrite time from the procedure and call the procedure on timer with the lastwrite time that was returned to you. Then you can compare the current time and the last time and do the refresh. On the first loop pass the current time and then keep using the lastread time in all subsequent calls and the result of which will keep updating the lastread time.

By : anil


The problem it that you are openning and closing file every time the timer ticks.
Open the file on TForm1.FormCreate by a TFileStream with fmOpenReadWrite or fmOpenShareDenyNone parameters, close it on TForm1.FormDestroy, and read it on TForm1.Timer1Timer if the number of read bytes are greater than zero convert the buffer to string and add it to the richedit.

By : Vahid


In your code

if filedate1 
By : MartynA


This video can help you solving your question :)
By: admin