限制面板内的图片框移动

时间:2015-08-09 06:13:13

标签: c#

我在c#中创建一个游戏应用程序,该面板中有面板和图片框。现在我想限制该面板边界内的那个图片框。我正在用keydown活动移动图片框。

    private void Form1_KeyDown(object sender, KeyEventArgs e)
    {

         if (e.KeyCode == Keys.Left)
         {


            pictureBox1.Left -= 10;


               //po = position.Left;
         }

        else if (e.KeyCode == Keys.Right)
        {


            pictureBox1.Left += 10;
           // po = position.Right;
        }
        else if (e.KeyCode == Keys.Up)
        {
            pictureBox1.Top -= 10;
           // po = position.Up;
        }
        else if (e.KeyCode == Keys.Down)
        {
            pictureBox1.Top +=10;
           // po = position.Down;
        }

    }

1 个答案:

答案 0 :(得分:1)

在您的情况下,最好使用开关语句。

以下代码经过测试并正常运行。您只需设置根据 PictureBox 面板的高度/宽度计算的最大值。

private void Form1_KeyDown(object sender, KeyEventArgs e)
{
    int borderMargin = 5;
    int stepSize = 10;    

    switch (e.KeyCode)
    {
        case Keys.Left:
        {
            int newLeft = Math.Max(0, pictureBox1.Left - stepSize);
            pictureBox1.Left = newLeft;
            break;
        }
        case Keys.Right:
        {
            int maxVal = panel1.Width - pictureBox1.Width - borderMargin;
            int newLeft = Math.Min(maxVal, pictureBox1.Left + stepSize);
            pictureBox1.Left = newLeft;
            break;
        }
        case Keys.Up:
        {
            int newTop = Math.Max(0, pictureBox1.Top - stepSize);
            pictureBox1.Top = newTop;
            break;
        }
        case Keys.Down:
        {
            int maxVal = panel1.Height - pictureBox1.Height - borderMargin;
            int newTop = Math.Min(maxVal, pictureBox1.Top + stepSize);
            pictureBox1.Top = newTop;
            break;
        }
    }
}

根据您的borderMargin配置,根据您的需要设置stepSizeForm