我是 c# 的新手-我想在按下 enter 时触发按钮单击事件。我的代码无法正常工作 -
问题是,当我在提交某些值时按 Enter 键时,它会显示应该显示的消息框,但是在按 Enter 键以获得 Messagebox 的 OK 按钮时,即使我没有按 Enter 键或输入任何其他值,它也会再次自动触发按钮单击事件。
public partial class Form1 : Form
{
int n1, n2 = 0;
private static readonly Random getrandom = new Random();
private static readonly object syncLock = new object();
public int GetRandomNumber(int min, int max)
{
lock (syncLock)
{ // synchronize
return getrandom.Next(min, max);
}
}
public int tQuestion()
{
n1 = GetRandomNumber(2, 11);
n2 = GetRandomNumber(2, 11);
string tQues = n1 + " x " + n2 + " = ";
label1.Text = tQues;
return 0;
}
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
tQuestion();
}
private void label1_Click(object sender, EventArgs e)
{
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
textBox1.KeyDown += new KeyEventHandler(tb_KeyDown);
}
public void button1_Click(object sender, EventArgs e)
{
string tAns = textBox1.Text;
int answer = n1 * n2;
string tOrgAns = answer.ToString();
if (tAns == tOrgAns)
MessageBox.Show("Your answer is Corect", "Result", MessageBoxButtons.OK,MessageBoxIcon.Exclamation );
else
MessageBox.Show("Your answer is WRONG", "Result", MessageBoxButtons.OK, MessageBoxIcon.Stop);
textBox1.Text = "";
textBox1.Focus();
tQuestion();
}
static void tb_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
button1_Click(sender, e);
}
}
此外,代码仅在我static
从中删除时才有效static void tb_KeyDown(object sender, KeyEventArgs e)
- 否则会出错:
非静态字段、方法或属性需要对象引用
请帮助我 - 我是 C# 和 .Net 的新手