检测输入键 C#
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11984238/
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
Detect Enter Key C#
提问by k1f1
I have the following code which does not show the MessageBox when enter/return is pressed.
我有以下代码,当按下输入/返回时不显示 MessageBox。
For any other key(i.e. letters/numbers) the MessageBox shows False.
对于任何其他键(即字母/数字),MessageBox 显示 False。
private void cbServer_TextChanged(object sender, EventArgs e)
{
if (enterPressed)
{
MessageBox.Show("Enter pressed");
}
else
MessageBox.Show("False");
}
private void cbServer_Keydown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter || e.KeyCode == Keys.Return)
{
enterPressed = true;
MessageBox.Show("Enter presssed: " + enterPressed);
}
else
enterPressed = false;
}
Any ideas?
有任何想法吗?
EDIT: Above code, I thought the issue was with the _Keydown even so I only posted that.
编辑:上面的代码,我认为问题出在 _Keydown 上,所以我只发布了它。
采纳答案by Renatas M.
This is because when you press EnterTextChangedevent won't fire.
这是因为当您按下EnterTextChanged事件时不会触发。
回答by Maziar Aboualizadehbehbahani
in your form designer class (formname.designer.cs) add this :
在您的表单设计器类 (formname.designer.cs) 中添加以下内容:
this.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.Login_KeyPress);
and add this code to backbone code (formname.cs):
并将此代码添加到主干代码 (formname.cs):
void Login_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == (char)13)
MessageBox.Show("ENTER has been pressed!");
else if (e.KeyChar == (char)27)
this.Close();
}
回答by MD. ROKON-UZ-ZAMAN
private void textBox_PreviewKeyDown(object sender, KeyEventArgs e)
{
if (e.Key == Key.Enter)
{
MessageBox.Show("Enter key pressed");
}
else if (e.Key == Key.Space)
{
MessageBox.Show("Space key pressed");
}
}
Use PreviewKeyDown event to detect any key before shown in textbox or input
使用 PreviewKeyDown 事件在文本框或输入中显示之前检测任何键

