移动表单上的按钮时出现 Delphi 访问冲突 [英] Delphi Access Violation when moving button on form
问题描述
我正在尝试使用 while 循环检查按钮 left 属性来移动表单上的 2 个按钮,但我遇到了访问冲突.我正在使用 CreateThread() 执行程序
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;
但是,当我使用至少 5 毫秒的 Sleep() 时,我没有访问冲突,如下所示:
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?
提前谢谢!
推荐答案
我正在使用
CreateThread()
执行该过程.
那是你的问题.VCL 代码只能从主 UI 线程调用.使用 TThread.Synchronize
在主线程上调用 VCL 代码.
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.
这篇关于移动表单上的按钮时出现 Delphi 访问冲突的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!