So within my program, I want an object to move left or right depending on what arrow key is held down. I moved the the picture box on the bottom of them form so when any of the two arrow keys are pressed they would move along the bottom. But what's happening is when I press either key, the picture box goes to the top and moves left and right there. I don't know why this is.
Here's the code for the Form1, ignore the code for Form2; that's for experimentation purpose right now:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Move
{
public partial class Form1 : Form
{
public int lives = 0;
Form2 menu = new Form2();
public Form1()
{
InitializeComponent();
}
private void button1_KeyDown(object sender, KeyEventArgs e)
{
}
private void pictureBox1_Click(object sender, EventArgs e)
{
}
private void Form1_KeyDown(object sender, KeyEventArgs e)
{
int i;
for (i = 0; i < 500; i++)
{
if (e.KeyCode == Keys.Left)
{
pictureBox1.Location = new Point(pictureBox1.Left - 1);
Application.DoEvents();
System.Threading.Thread.Sleep(10);
}
if (e.KeyCode == Keys.Right)
{
pictureBox1.Location = new Point(pictureBox1.Left + 1);
Application.DoEvents();
System.Threading.Thread.Sleep(10);
}
var rect1 = new System.Drawing.Rectangle(pictureBox1.Location, pictureBox1.Size);
var rect2 = new System.Drawing.Rectangle(pictureBox2.Location, pictureBox2.Size);
if (rect1.IntersectsWith(rect2))
{
MessageBox.Show("Game Over!");
System.Threading.Thread.Sleep(1000);
Application.Exit();
}
if (e.KeyCode == Keys.Down)
{
this.Hide();
menu.Show();
}
}
}
}
}