我的表单中有两个按钮、一个标签和一个计时器控件。在timer tick事件中,我做到了:
private void timer2_Tick(object sender, EventArgs e)
{
if (mode == "Left-to-Right")
{
if (this.Width == xpos)
{
this.label1.Location = new System.Drawing.Point(0, ypos);
xpos = 0;
}
else
{
this.label1.Location = new System.Drawing.Point(xpos, ypos);
xpos += 2;
}
}
else if (mode == "Right-to-Left")
{
if (xpos == 0)
{
this.label1.Location = new System.Drawing.Point(this.Width, ypos);
xpos = this.Width;
}
else
{
this.label1.Location = new System.Drawing.Point(xpos, ypos);
xpos -= 2;
}
}
}然后出现一个按钮单击事件:
private void button2_Click_1(object sender, EventArgs e)
{
xpos = label2.Location.X;
ypos = label2.Location.Y;
mode = "Left-to-Right";
timer2.Start();
}和一个按钮点击事件:
private void button3_Click_1(object sender, EventArgs e)
{
xpos = label2.Location.X;
ypos = label2.Location.Y;
mode = "Right-to-Left";
timer2.Start();
}当我单击button2使其从左向右移动时,它工作正常。当文本到达右侧的末尾时,文本就像从边界内移出边界,然后从左侧返回。
但是,当我从右向左单击按钮时,一旦文本到达左侧边界/边框的末尾,文本就会消失/消失一秒钟,然后从原来的位置开始移动。为什么它的行为不像在button2上那样从左到右?
编辑**
以下是我所做的更改:
private void timer2_Tick(object sender, EventArgs e)
{
if (mode == "Left-to-Right")
{
if (this.Width == xpos)
{
this.label1.Location = new System.Drawing.Point(0, ypos);
xpos = 0;
}
else
{
this.label1.Location = new System.Drawing.Point(xpos, ypos);
xpos += 2;
}
}
else if (mode == "Right-to-Left")
{
if (xpos < -label2.Width)
{
this.label1.Location = new System.Drawing.Point(this.Width, ypos);
xpos = this.ClientSize.Width - label2.Width;
}
else
{
this.label1.Location = new System.Drawing.Point(xpos, ypos);
xpos -= 2;
}
}
}发布于 2014-04-04 14:53:35
如果this.Width是奇数,这将不起作用。尝试更改此设置
if (this.Width == xpos)要这样做:
if (this.Width >= xpos)通常情况下,最好不要测试数字是否相等。测试greater than、less than或greater or equal。这就是所谓的防御性编程,它不会让你付出任何代价,而且会让你的代码更健壮。
https://stackoverflow.com/questions/22855225
复制相似问题