【问题标题】:Modifying randomly button location随机修改按钮位置
【发布时间】:2016-03-13 23:06:12
【问题描述】:

我试图在鼠标悬停时随机更改按钮的位置。为此,我使用以下源代码:

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

问题是我的按钮位置总是在一条直线上,比如that

我该如何解决?我尝试使用 bt_win.Location.X = modifX();在 mouseEnter 事件上但似乎我无法处理 Location.X 或 Location.Y 我真的不明白我做错了什么,有人有想法并可以解释我做错了什么吗?

【问题讨论】:

    标签: c# button random location


    【解决方案1】:

    您需要使用 Random 类的相同实例。 当您紧密地创建 Random 类的两个实例时,它们可以共享相同的种子。所以会生成相同的数字。

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

    【讨论】:

    • 非常感谢!但是我真的不明白为什么我需要使用相同的 Random 类实例,你能解释一下吗?
    • 因为创建实例时,使用的是当前时间。见this
    • 感谢您的帮助和解释的来源!了解随机数是一件很有用的事情。
    猜你喜欢
    • 1970-01-01
    • 2019-03-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多