Home > Enterprise >  How could I change the location of a button whenever it is pressed in C#?
How could I change the location of a button whenever it is pressed in C#?

Time:05-22

I am currently trying to make a game in C#, and one of the features is a minigame in which you have to press a button which changes location upon click as many times as you can.

How could I randomise the location of it between (12, 105) and (220, 177)? I'm using Visual Studio 2022.

    private void button1_Click(object sender, EventArgs e)
    {
        clicks  ;
    }

CodePudding user response:

Assuming that you use WinForms, you can put it as follow:

 static readonly Random s_Random = new Random();

 private void button1_Click(object sender, EventArgs e) {
   clicks  ;

   button1.Location = new Point(
     s_Random.Next(12, 220   1), // x (left) in [12..220] range
     s_Random.Next(105, 177   1) // y (top) in [105..177] range
   ); 
 }

CodePudding user response:

  1. In order to generate random values, you can use the Random class.
    As you can see in the documentation above, in order to get an integer value between a and b, you need to use:
Random rand = new Random();
int val = rand.Next(a, b 1);
  1. In order to move a button, you can modify it's Left, and Top properies. This applies to WinForms, but WPF has similar properties.

The code below demonstrates both:

// Can be kept as a class member:
Random rand = new Random(); 

// Note: change x1,x2,y1,y2 below to control the range for locations.
int x1 = 12;
int x2 = 220;
int y1 = 105;
int y2 = 177;
// Randomize location in the defined range:
int x = rand.Next(x1, x2   1);
int y = rand.Next(y1, y2   1);
// Move the button:
button1.Left = x;
button1.Top = y;
  •  Tags:  
  • c#
  • Related