如何在不离开pictureBox区域的情况下移动pictureBox1内的按钮?

时间:2014-03-02 20:02:42

标签: c# winforms

private void timer1_Tick(object sender, EventArgs e)
        {
            int x = r.Next(0, pictureBox1.Width);
            int y = r.Next(0, pictureBox1.Height);
            button1.Top = y;
            button1.Left = x;
        }

        private void button2_Click(object sender, EventArgs e)
        {

        }

编辑**

int x1 = r.Next(0, pictureBox1.Width);
            int y1 = r.Next(0, pictureBox1.Height);
            randomPoint = new Point(x1, y1);
            if (currentPosition.X != randomPoint.X)
            {
                if (currentPosition.X > randomPoint.X)
                    currentPosition.X -= 1;
                else
                    currentPosition.X += 1;

                button1.Location = currentPosition;
            }
            else if (currentPosition.Y != randomPoint.Y)
            {
                if (currentPosition.Y > randomPoint.Y)
                    currentPosition.Y -= 1;
                else
                    currentPosition.Y += 1;

                button1.Location = currentPosition;
            }
            else
            {
                randomPoint.X = r.Next(0, pictureBox1.Width - button1.Width - 1);
                randomPoint.Y = r.Next(0, pictureBox1.Height - button1.Height - 1);
            }

在表格的顶部我做了:

int x ;
int y ;
Point currentPosition;
Point randomPoint;

在构造函数中:

x = button1.Location.X; y = button1.Location.Y; currentPosition = new Point(x,y);

1 个答案:

答案 0 :(得分:1)

在表单加载事件中执行:

currentPosition = button1.Location;
randomPoint.X = r.Next(0, PictureBox1.Width - Button1.Width - 1);
randomPoint.Y = r.Next(0, PictureBox1.Height - Button1.Height - 1);

在计时器内:

if(currentPosition.X != randomPoint.X){
    if (currentPosition.X > randomPoint.X)
        currentPosition.X -= 1;
    else
        currentPosition.X += 1;

    Button1.Location = currentPosition;
}
else if(currentPosition.Y != randomPoint.Y){
    if(currentPosition.Y > randomPoint.Y)
        currentPosition.Y -= 1;
    else
        currentPosition.Y += 1;

    Button1.Location = currentPosition;
}
else{
    randomPoint.X = r.Next(0, PictureBox1.Width - Button1.Width - 1);
    randomPoint.Y = r.Next(0, PictureBox1.Height - Button1.Height - 1);
}

就移动而言,您可以增加picturebox尺寸or(and) dicrease button大小。 不要忘记在Random r = new Random();currentPosition声明randomPoint

瓦尔特