防止PictureBox离开屏幕

时间:2016-03-30 18:39:15

标签: c# winforms

我在C#中创建了一个Windows窗体应用程序。有一个名为YourCube的图片框根据按下的键移动,W,A,S和D.我想阻止它离开屏幕,我在这里看到类似Prevent mouse from leaving my form的答案

private int X = 0;
private int Y = 0;

private void Form1_MouseLeave(object sender, EventArgs e)
{
    Cursor.Position = new Point(X, Y);
}

private void Form1_MouseMove(object sender, MouseEventArgs e)
{
    if (Cursor.Position.X < this.Bounds.X + 50 )
        X = Cursor.Position.X + 20;
    else
        X = Cursor.Position.X - 20;

    if (Cursor.Position.Y < this.Bounds.Y + 50)
        Y = Cursor.Position.Y + 20;
    else
        Y = Cursor.Position.Y - 20;           
}

但对于鼠标。我该怎么做图片框?

1 个答案:

答案 0 :(得分:0)

在按下的每个键上,只有在PictureBox不会脱离表单边界时才移动,如下所示:

private void MoveW() {
    if (YourCube.Top > 0) {
        YourCube.Location = new Point(YourCube.Left, YourCube.Top -1);
    }
}

private void MoveA() {
    if (YourCube.Left > 0) {
        YourCube.Location = new Point(YourCube.Left - 1, YourCube.Top);
    }
}

private void MoveS() {
    if (YourCube.Top + YourCube.Height < form1.ClientRectangle.Height) {
        YourCube.Location = new Point(YourCube.Left, YourCube.Top + 1);
    }
}

private void MoveD() {
    if (YourCube.Left + YourCube.Width < form1.ClientRectangle.Width) {
        YourCube.Location = new Point(YourCube.Left + 1, YourCube.Top);
    }
}