Delphi Access Violation when moving button on form

旧街凉风 提交于 2019-12-19 11:54:25

问题


I am trying to move 2 buttons on the form using a while loop checking for the buttons left property, but I have an Access Violation. I am exeting the procedure with CreateThread()

The code:

procedure AnimButton1();
var ImageCount: integer;
var b1, b2: integer;
begin

  try

       while (b2 <> 187) do
       begin
           b2 := frmNotification.btnBuzina2.Left;
           frmNotification.btnBuzina2.Left := b2 - 1;

       end;

       while (b1 <> 256) do
       begin
           b1 := frmNotification.btnBuzina.Left;
           frmNotification.btnBuzina.Left := b1 - 1;

       end;

  except;
  end;

end;

BUT, when I use a Sleep() with at least 5 miliseconds, I dont have an access violation, like this:

procedure AnimButton1();
var ImageCount: integer;
var b1, b2: integer;
begin

  try

       while (b2 <> 187) do
       begin
           b2 := frmNotification.btnBuzina2.Left;
           frmNotification.btnBuzina2.Left := b2 - 1;
           Sleep(5);
       end;

       while (b1 <> 256) do
       begin
           b1 := frmNotification.btnBuzina.Left;
           frmNotification.btnBuzina.Left := b1 - 1;
           Sleep(5);
       end;

  except;
  end;

end;

Could someone help me to find out why without the sleep I get the access violation and with it I dont?

thx in advance!


回答1:


I am executing the procedure with CreateThread().

That is your problem. VCL code must only be called from the main UI thread. Use TThread.Synchronize to invoke the VCL code on the main thread.

That said, a timer might be a more appropriate solution to you problem than a thread.



来源:https://stackoverflow.com/questions/30705750/delphi-access-violation-when-moving-button-on-form

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!