0

I'm trying to change randomly the location of a button when the mouse is hover it. To do that, I'm using the following source code :

    private int modifX()
    {
        int rdmx;
        int x_max = this.Width;
        Random rdm = new Random();
        rdmx = rdm.Next(0, x_max);
        return rdmx;
    }

    private int ModifY(){
      // same with y_max = this.Height;
    } 

    private void bt_win_MouseEnter(object sender, EventArgs e)
    {
        bt_win.Location = new Point(modifX(), modifY());
    }

The problem is that my button's position is always on a straight line like that

How can I fix it? I tried to use bt_win.Location.X = modifX(); on the mouseEnter event But it seems that I can't handle Location.X or Location.Y I don't really get what I'm doing wrong, anyone got an idea and could explain me what I'm doing wrong?

Y.Paulet
  • 47
  • 1
  • 8

1 Answers1

0

You need to use the same instance of the Random class. When you create two instance of the Random class closely, they can share the same seed. So the same number will be generated.

private Random _rdm = new Random();

private int modifX()
{
    int x_max = this.Width;
    int rdmx = _rdm.Next(0, x_max);
    return rdmx;
}

private int ModifY(){
  // same with y_max = this.Height;
} 

private void bt_win_MouseEnter(object sender, EventArgs e)
{
    bt_win.Location = new Point(modifX(), modifY());
}
Kalten
  • 4,092
  • 23
  • 32
  • It's working thanks a lot! But I don't really understand why do I need to use the same Random class instance, could you please explain me? – Y.Paulet Mar 13 '16 at 23:14
  • Because when you create the instance, the current time is used. See [this](http://stackoverflow.com/questions/767999/random-number-generator-only-generating-one-random-number) – Kalten Mar 13 '16 at 23:24
  • Thanks for the help and the source for the explanation! That's an useful thing to know with random numbers. – Y.Paulet Mar 13 '16 at 23:28