在timer事件中完成label的滚动
timer1.temer()
dim i as type
a) if label1.left<=0 then i=0
b) if label1.left>=form1.width-label1.width then i=1
c) if i=0 then label1.left =label1.left +20
d) if i=1 then label1.left =label1.left -20
end sub
在以上的代码中,想实现label的来回滚动,但运行结果是:label1在运行到form的右端时,就在此处左右小幅度的晃动,不再往回走。
究其原因在于:在dim i as type 的时候,i的默认值是0,所以label能顺利执行c)语句,运动到form的右端,当到右端时满足了b)语句,此时i=1,于是又运行d)语句,但是timer事件的特点在于能够随时间在一定的interval间隔中更新,循环timer事件,所以当满足一定的interval间隔后,就会执行一次timer,重新定义变量i,所以i的默认值又为0了,所以label在上一次到达的位置向右移动……如此循环下去,就形成了label在form的右端来回晃动。
怎样才能让label1来回在form中来回滚动呢?
解决办法:
方法1:
把dim i as type 放在窗体模块的通用声明部分。这样的好处是i每次都可以保留一下它的值,所以当i=1 时,timer在循环时能够保留上次循环i得到的值。这样,label就能实现来回滚动。
代码如下:
dim i as type
timer1.temer()
a) if label1.left<=0 then i=0
b) if label1.left>=form1.width-label1.width then i=1
c) if i=0 then label1.left =label1.left +20
d) if i=1 then label1.left =label1.left -20
end sub
方法2:
在timer事件中可以声明i的类型是static类型。这样也可以保留原来循环的值,让label来回滚动下去。
代码如下:
timer1.temer()
static i as type
a) if label1.left<=0 then i=0
b) if label1.left>=form1.width-label1.width then i=1
c) if i=0 then label1.left =label1.left +20
d) if i=1 then label1.left =label1.left -20
end sub