简体   繁体   English

在窗体上移动按钮时发生Delphi访问冲突

[英]Delphi Access Violation when moving button on form

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. 我正在尝试使用while循环检查按钮的left属性来在窗体上移动2个按钮,但是我遇到了访问冲突。 I am exeting the procedure with CreateThread() 我正在用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: 但是,当我使用Sleep()至少5毫秒时,我没有访问冲突,如下所示:

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! 提前谢谢!

I am executing the procedure with CreateThread() . 我正在使用CreateThread()执行该过程。

That is your problem. 那是你的问题。 VCL code must only be called from the main UI thread. VCL代码只能从主UI线程调用。 Use TThread.Synchronize to invoke the VCL code on the main thread. 使用TThread.Synchronize在主线程上调用VCL代码。

That said, a timer might be a more appropriate solution to you problem than a thread. 也就是说,计时器可能比线程更适合解决您的问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM