2

I made a Windows Forms Aplication in C#. There's picture box called YourCube which moves according to the key pressed, W,A,S and D. I want to prevent it from leaving the screen, I've seen something similar here Prevent mouse from leaving my form with the answer

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;           
}

but for the mouse. How can I do it for the Picture Box?

Community
  • 1
  • 1
Alex Kayz
  • 191
  • 1
  • 15
  • 2
    The solution is fundementally the same as the one you linked. You just have to do the bounds checking in whatever method is doing the moving (Hopefully a method called by a keypress event handler) – Jason Watkins Mar 30 '16 at 18:42

1 Answers1

0

On each key pressed, only move if the PictureBox will not get out of the form bounds, something like this:

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);
    }
}
LoRdPMN
  • 512
  • 1
  • 5
  • 18
  • Thanks LoRdPMN, I'v addded the IF whenever a key is pressed to make sure you don't get out of the bounds. Thanks again ! – Alex Kayz Mar 30 '16 at 18:55