令小弟我迷惑的Sleep
令我迷惑的Sleep
问题(BCB的,不过跟Delphi类似)
1:在窗体上,加入TButton 和TLabel
2:在Button的单击事件中:
void __fastcall TForm1::Button1Click(TObject *Sender)
{
Label1-> Caption=0;
for(int i=1;i <=10;i++)
{
Label1-> Caption=i;
Sleep(100);
}
}
目的是想让Label-> Caption依次显示1,2,3,.....10
为使 每个数字显示1秒,加入Sleep(1000),相当于线程停止执行1秒,
运行结果如下:
单击Button后,Label1-> Caption无变化,一直为0.等到10秒后,直接由0变为10.
这就奇怪了,为什么不依次1,2,3,4,5,6,7,8,9,10,而是依次就变为10?
兄弟们来看看呀???
------解决方案--------------------
线程停止,没处理重绘消息
void __fastcall TForm1::Button1Click(TObject *Sender)
{
Label1-> Caption=0;
for(int i=1;i <=10;i++)
{
Label1-> Caption=i;
Label2-> Update;
Sleep(100);
}
}
------解决方案--------------------
Label1-> Caption=i;
Label1-> Refresh(); //加上次句就行了
Sleep(1000);
问题(BCB的,不过跟Delphi类似)
1:在窗体上,加入TButton 和TLabel
2:在Button的单击事件中:
void __fastcall TForm1::Button1Click(TObject *Sender)
{
Label1-> Caption=0;
for(int i=1;i <=10;i++)
{
Label1-> Caption=i;
Sleep(100);
}
}
目的是想让Label-> Caption依次显示1,2,3,.....10
为使 每个数字显示1秒,加入Sleep(1000),相当于线程停止执行1秒,
运行结果如下:
单击Button后,Label1-> Caption无变化,一直为0.等到10秒后,直接由0变为10.
这就奇怪了,为什么不依次1,2,3,4,5,6,7,8,9,10,而是依次就变为10?
兄弟们来看看呀???
------解决方案--------------------
线程停止,没处理重绘消息
void __fastcall TForm1::Button1Click(TObject *Sender)
{
Label1-> Caption=0;
for(int i=1;i <=10;i++)
{
Label1-> Caption=i;
Label2-> Update;
Sleep(100);
}
}
------解决方案--------------------
Label1-> Caption=i;
Label1-> Refresh(); //加上次句就行了
Sleep(1000);