我是 c# 新手 - 我想在按 Enter 时触发按钮单击事件。我的代码无法正常工作 -
问题是,当我按 Enter 键提交某些值时,它会显示应该显示的消息框,但是在按 Enter 键确认消息框的“确定”按钮时,即使我不按 Enter 键或输入任何其他内容,它也会自动再次触发按钮单击事件值(value)。
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)
- 否则会出现错误:
An object reference is required for the non-static field, method, or property
请帮助我 - 我是 c# 和 .Net 新手
最佳答案
将按钮点击事件处理程序提取到单独的方法中(例如VerifyAnswer
)并从两个地方调用它:
public void button1_Click(object sender, EventArgs e)
{
VerifyAnswer();
}
// NOTE: static modifier removed
private void tb_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
VerifyAnswer();
}
private void VerifyAnswer()
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();
}
不要尝试手动执行事件处理程序 - 它们的目的只是处理事件。
关于c# - 按 Enter 键时调用按钮单击事件 - c#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17811136/