按 Enter 时调用按钮单击事件 - c#
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17811136/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Call button click event on pressing Enter - c#
提问by
I am new to c# - I want to trigger button click event on pressing enter. My code not working properly -
我是 c# 新手 - 我想在按下 Enter 键时触发按钮单击事件。我的代码无法正常工作 -
issue is that when i press enter on submitting some value, it displays messagebox which it should show but on pressing Enter for OK button of Messagebox, it automatically triggers button click event again even i don't press enter or enter any other value.
问题是,当我在提交某些值时按 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);
}
}
Moreover, code only works if i remove static
from static void tb_KeyDown(object sender, KeyEventArgs e)
- otherwise it gives error:
此外,如果我删除代码只能static
从static void tb_KeyDown(object sender, KeyEventArgs e)
-否则提示错误:
An object reference is required for the non-static field, method, or property
非静态字段、方法或属性需要对象引用
Please help me - i am new to c# & .Net
请帮助我 - 我是 c# 和 .Net 的新手
采纳答案by Shumail
You are calling while textbox is focused. Better option is to create a separate function and call that from both.
您在文本框聚焦时调用。更好的选择是创建一个单独的函数并从两者中调用它。
I have made changes to your code. It's working for me. You need to link tb_keyDown
event with keyDown
property in Textbox Properties.
我已经对您的代码进行了更改。它对我有用。您需要将tb_keyDown
事件与keyDown
文本框属性中的属性相关联。
Try this code:
试试这个代码:
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)
{
//make it empty. You need to attach tb_KeyDown event in properties
}
public void button1_Click(object sender, EventArgs e)
{
CheckAnswer();
}
void tb_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
CheckAnswer();
}
}
private void CheckAnswer()
{
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();
}
}
回答by Sergey Berezovskiy
Extract button click event handler into separate method (e.g. VerifyAnswer
) and call it from both places:
将按钮单击事件处理程序提取到单独的方法(例如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();
}
Don't try to manually execute event handlers - their purpose is handling events only.
不要尝试手动执行事件处理程序 - 它们的目的只是处理事件。
回答by Microtechie
You cannot access instance members from static members
您不能从静态成员访问实例成员
Either you have to
要么你必须
- Make the method an instance method (remove the static keyword)
- Make the field/method a static (add the static keyword)
- 使方法成为实例方法(去掉 static 关键字)
- 使字段/方法成为静态(添加 static 关键字)
The one you choose will depend on whether the field should be shared across all instances or not.
您选择的那个取决于是否应该在所有实例之间共享该字段。
Hope it will help
希望它会有所帮助
回答by Oreflow
You might want to use a static parameterless keylistener, which you could have running separately in the static method to check for key input. And then parse the key inputs there
您可能想要使用静态无参数 keylistener,您可以在静态方法中单独运行以检查键输入。然后解析那里的关键输入
回答by Mike Perrenoud
That's because of this code:
那是因为这段代码:
static void tb_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
button1_Click(sender, e);
}
}
Remove that handler and set the AcceptButton
of the Form
to button1
. The AcceptButton
is a property you can simply set in the designer.
删除处理程序和设置AcceptButton
的Form
到button1
。这AcceptButton
是您可以在设计器中简单设置的属性。
回答by alex555
Are you looking for that
你在找那个吗
button1.PerformClick()
回答by George Johnston
Don't attempt to triggera button click. Essentially what you should do is refactor your code so that the event handlers are separated from the actual implementation. e.g.
不要试图触发按钮点击。本质上,您应该做的是重构您的代码,以便将事件处理程序与实际实现分开。例如
ButtonClick(...)
{
ExecuteMethod();
}
KeyDown(...)
{
ExecuteMethod();
}
ExecuteMethod()
{
// Actual implementation.
}
This disassociates the event you are subscribing to from the implementation. That way, in the future, if you wish to add new buttons or change around event handlers, your actual logical implementation remains unchanged.
这将您订阅的事件与实现分离。这样,将来,如果您希望添加新按钮或更改事件处理程序,您的实际逻辑实现将保持不变。
回答by Himanshu kamothi
please, check below options:
请检查以下选项:
(1)Can you not use AcceptButton in for the Forms Properties Window? This sets the default behaviour for the "Enter" key press, but you are still able to use other shortcuts. (2)
(1) 窗体属性窗口中不能使用 AcceptButton 吗?这设置了“Enter”键按下的默认行为,但您仍然可以使用其他快捷方式。(2)
static void tb_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == (char)13)
{
button1_Click(sender, e);
}
}