2016-03-30 10 views
2

C#でWindows Formsアプリケーションを作成しました。私は、画面を離れることを防止したい、W、A、S、Dの押されたキーに応じて移動YourCubeと呼ばれるピクチャボックスがあります、私はここでPrevent mouse from leaving my form答えPictureBoxが画面から離れないようにする

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

と同様のものを見てきましたが、マウスのために。ピクチャーボックスのためにどうすればいいですか?押された各キーの

+2

ソリューションはfundementallyリンクされたものと同じです。どのようなメソッドが動いているのかチェックするだけで境界をチェックする必要があります(keypressイベントハンドラによって呼び出されたうまくいけばメソッド) –

答えて

0

、ピクチャボックスは、フォームの境界の外に取得することはできません場合にのみ移動し、このような何か:

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); 
    } 
} 
+0

ありがとうLoRdPMN、私はキーが押し出されるたびにIFを追加しました限界の再度、感謝します ! –

関連する問題