Mahmoud Bitar
Mahmoud Bitar

Reputation: 33

Move the form dynamically c# with key pressed

I need to move the form location when I press A button, but not only one time, each time I pressed on the A button the form should appear in different location

private void Form1_KeyDown(object sender, KeyEventArgs e) 
 { 
    if (e.KeyCode == Keys.A)  // First time I press A
      form.Location = location1; 

    if (e.KeyCode == Keys.A) 
      form.Location = location2; // second time I press A

   if (e.KeyCode == Keys.A) 
      form.Location = location3; // 3rd time I press A


  } 

So when I press "A" the first time the form will be in location1, if 2nd time it will on location2, if 3rd time it will be on location3, if it's the 4th time it should return to location1...

Any ideas?

I tried to use int variable to check if it's the first time or 2nd or 3rd, but not working...

Upvotes: 1

Views: 86

Answers (2)

Perfect28
Perfect28

Reputation: 11317

Just put a basic counter and use the modulo operator.

private int timeKeyPress = 0; 

private void Form1_KeyDown(object sender, KeyEventArgs e) 
{ 
    Point locations = new Point[] {location1, location2, location3 };    

    if (e.KeyCode == Keys.A)
    {
         form.Location = locations[timeKeyPress++ % locations.Length]; 
    }  
} 

This assumes that if you press A more than 2,147,483,647 times the application will fail to IndexOutOfRangeException.

Upvotes: 2

Hazem Abdullah
Hazem Abdullah

Reputation: 1893

I think you need to store the location1, location2, location3 in an array or list

List<Point> arr_points = new List<Point>();

Then you need to fill this locations in form load for example

  private void Form1_Load(object sender, EventArgs e)
        {
            arr_points.Add(new Point(166, 516));
            arr_points.Add(new Point(36, 516));
            arr_points.Add(new Point(0, 0));
        }

And an int variable to be a counter

 int i = 0;

Then you need to check at key_down if this i is more than the arr_points then it should be 0 again, else you need to increase it i++

 private void Form1_KeyDown(object sender, KeyEventArgs e)
        {
            if (i == arr_points.Count)
            {
                i = 0;
            }
            if (e.KeyCode == Keys.A)
                this.Location = arr_points[i];
            i++;

        }

So the whole code will be like the following code:

List<Point> arr_points = new List<Point>();
 int i = 0;
 private void Form1_Load(object sender, EventArgs e)
        {
            arr_points.Add(new Point(500, 400));
            arr_points.Add(new Point(25, 516));
            arr_points.Add(new Point(0, 0));
        }



        private void Form1_KeyDown(object sender, KeyEventArgs e)
        {
            if (i == arr_points.Count)
            {
                i = 0;
            }
            if (e.KeyCode == Keys.A)
                this.Location = arr_points[i];
            i++;

        }

Upvotes: 1

Related Questions