Recent

Author Topic: [Solved] Access violation trying to create a timer  (Read 470 times)

Wilko500

  • Full Member
  • ***
  • Posts: 144
[Solved] Access violation trying to create a timer
« on: June 12, 2025, 01:48:04 am »
Following on from my last post https://forum.lazarus.freepascal.org/index.php/topic,71422.0.html the timer works as it should when started by a button on the main form, starts the timer and displays the date/time on main form

Code: Pascal  [Select][+][-]
  1. procedure TfrmMain.Button1Click(Sender: TObject);
  2. Var
  3.     MyTest: TMyTimer;
  4. begin
  5.     MyTest.Create;
  6.     MyTest.Start(1000, @DisplayTime);
  7. end;  
But I want it to start automatically when program starts so I put a call at the end of form.Activate and then got an Access violation.  I had something like this before when I tried to do something before the form was fully loaded/ready so I recoded to call the same code with Application.QueueAsyncCall at the end of Form.Activate.  This calls the same code
Code: Pascal  [Select][+][-]
  1. Procedure TfrmMain.StartTimers;
  2. Var
  3.     MyTest: TMyTimer;
  4. begin
  5.     MyTest.Create;  //<=  Access violation here
  6.     MyTest.Start(1000, @DisplayTime);
  7. End;{Procedure Timers}
which still gives an access violation
Code: Pascal  [Select][+][-]
  1. exception class 'Process stopped with reason: EXC_BAD_ACCESS (code=EXC_I386_GPFLT)'.
  2.  
  3. In file 'timerunit.pas' at line 30:
  4. FTimer := TTimer.Create(nil);

I am very puzzled as to why the same code works from a button but fails when run from Application.QueueAsyncCall.
« Last Edit: June 12, 2025, 07:37:59 pm by Wilko500 »
MacBook Pro mid 2015 with OS Monterey 12.7.6
FPC 3.2.3 Lazarus 3.7
FPC 3.2.2 Lazarus 3.4

dseligo

  • Hero Member
  • *****
  • Posts: 1532
Re: Access violation trying to create a timer
« Reply #1 on: June 12, 2025, 02:27:52 am »
You don't create TMyTimer correctly.

Do it like this:

Code: Pascal  [Select][+][-]
  1. Procedure TfrmMain.StartTimers;
  2. Var
  3.     MyTest: TMyTimer;
  4. begin
  5.     MyTest := TMyTimer.Create;  // <=  see this line
  6.     MyTest.Start(1000, @DisplayTime);
  7. End;{Procedure Timers}

Wilko500

  • Full Member
  • ***
  • Posts: 144
Re: Access violation trying to create a timer
« Reply #2 on: June 12, 2025, 07:37:29 pm »
Thank you @dseligo.  That's a duh-rr moment! And of course it's obvious when I look at it now.  Because the incorrect code, that I copied,  was working I was looking for a more complicated solution rather than the obvious. And it turns out that I can run the StartTimers procedure from form.Activate as I wanted to.
MacBook Pro mid 2015 with OS Monterey 12.7.6
FPC 3.2.3 Lazarus 3.7
FPC 3.2.2 Lazarus 3.4

 

TinyPortal © 2005-2018