using System;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace RandomNumbers
{
public partial class frmRandomNumberGenerator : Form
{
private bool generate = true;
public frmRandomNumberGenerator()
{
InitializeComponent();
}
private string GenerateNumber(int min, int max)
{
return new Random().Next(min, max).ToString();
}
private void ToggleControls()
{
btnStart.Enabled = !generate;
tcRandomNumbers.Enabled = !generate;
txtRangeMin.Enabled = !generate;
txtRangeMax.Enabled = !generate;
btnStop.Enabled = generate;
}
private async void btnStart_Click(object sender, EventArgs e)
{
if(string.IsNullOrEmpty(txtRangeMin.Text) || string.IsNullOrEmpty(txtRangeMax.Text))
{
MessageBox.Show("Invalid range!");
return;
}
int min = 0;
int max = 0;
bool result = int.TryParse(txtRangeMin.Text, out min);
if (result) result = int.TryParse(txtRangeMax.Text, out max);
if (result) result = max > min;
if (!result)
{
MessageBox.Show("Invalid range!");
return;
}
generate = true;
ToggleControls();
while (true)
{
if (!generate) break;
if (tcRandomNumbers.SelectedIndex == 0)
{
lblSingleResult.Text = GenerateNumber(min, max);
}
else
{
lblSequenceFirst.Text = GenerateNumber(min, max);
lblSequenceSecond.Text = GenerateNumber(min, max);
lblSequenceThird.Text = GenerateNumber(min, max);
lblSequenceFourth.Text = GenerateNumber(min, max);
lblSequenceFifth.Text = GenerateNumber(min, max);
}
await Task.Delay(TimeSpan.FromSeconds(1));
}
}
private void btnStop_Click(object sender, EventArgs e)
{
generate = false;
ToggleControls();
}
}
}
答案 0 :(得分:1)
有关详细信息,请参阅链接的答案。
变化:
private string GenerateNumber(int min, int max)
{
return new Random().Next(min, max).ToString();
}
要:
private Random rnd = new Random();
private string GenerateNumber(int min, int max)
{
return rnd.Next(min, max).ToString();
}
另外,请注意" max"将不包含在可能的返回值中。为此你需要:
return rnd.Next(min, max + 1).ToString();