Show message only once

Below is the code in the OnTimer event. If elements from 2 lists do not match - ShowMessage. I only need to show the message once, but since the timer is running, the message keeps showing up at the given timer interval. I tried to disable the timer after the ShowMessage line, but then the message will even show.

for i := 0 to ListBox2.Items.Count - 1 do begin
  p := ListBox1.Items.IndexOf(ListBox2.Items[i]);
  if p = -1 then
    ShowMessage('not matching');
end;

      

Thank.

+2


source to share


4 answers


I suspect what you did was include: = false after the message box. put allowed: = false in front of the message field and it should work:

var
  i : integer;
  p : integer;

begin

  for i := 0 to ListBox2.Items.Count - 1 do begin
    p := ListBox1.Items.IndexOf(ListBox2.Items[i]);
    if p = -1 then begin
      timer1.Enabled := false;
      ShowMessage('not matching');
      break;
    end;
  end;

      



Best wishes don

+5


source


Try to make another variable (type example Boolean

) and store it False if the message isn't shown yet, True when it is displayed and change the condition to something like this:

if (p = -1) and not messageShown then ...

      



Remember to change messageShown

to True after the first time the message appears.

+2


source


Another possible solution is the following:

  timer1.Enabled := false; // <---

  for i := 0 to ListBox2.Items.Count - 1 do begin
    p := ListBox1.Items.IndexOf(ListBox2.Items[i]);
    if p = -1 then
    begin
      ShowMessage('not matching');
      exit;  // <---
    end;
  end;

  timer1.Enabled := true; // <---

      

If the lists do not match, this code shows a message and disables the timer.
Of course, in this case, you will have to include it from some other procedure.

+1


source


Was the line turned off by a timer inside the if block, or was it executed on each iteration of the loop? If it were me, I would set a flag indicating that the message should be shown and then exit the loop. After the loop, I would check to see if the message should be shown, and if so, both show the message and turn off the timer. Presumably the timer gets reset when the items in the lists change so that the check will run again.

Caveat: I'm not a Delphi programmer; I'm only talking in general terms about how I structured it. If what I said doesn't make sense from a Delphi perspective, please comment and I'll delete my answer.

0


source







All Articles