控件移动,触碰边缘改变方向

csharp

浏览数:559

2019-1-7

private async void Form1_Load(object sender, EventArgs e)
{
    var pic = new PictureBox();
    pic.ImageLocation = "Image\\1.jpg";
    pic.Location = new Point(0, 0);
    pic.Size = new Size(120, 80);
    pic.SizeMode = PictureBoxSizeMode.Zoom;
    Controls.Add(pic);

    void SetDirection(out int a, out int b)
    {
        var rnd = new Random();
        a = (int) (rnd.NextDouble() * 50) - 25;
        b = (int) (rnd.NextDouble() * 50) - 25;
    }

    SetDirection(out int x, out int y);
    while (true)
    {
        pic.Location = new Point(pic.Location.X + x, pic.Location.Y + y);

        if (pic.Left >= 0 && pic.Left <= ClientSize.Width - pic.Size.Width && pic.Top >= 0 &&
            pic.Top <= ClientSize.Height - pic.Size.Height)
        {
            await Task.Delay(50);
        }
        else
        {
            pic.Location = new Point(pic.Location.X - x, pic.Location.Y - y);
            SetDirection(out x, out y);
        }
    }
}