C# 为什么按键关闭事件不会触发?
我的初衷是让文本框的enter事件运行btnOK_Click事件,但几次尝试后我都无法实现,所以我尝试了另一种方法,并尝试按任意键,但仍然不起作用,所以我编写了这两个简单的代码,但仍然不起作用C# 为什么按键关闭事件不会触发?,c#,C#,我的初衷是让文本框的enter事件运行btnOK_Click事件,但几次尝试后我都无法实现,所以我尝试了另一种方法,并尝试按任意键,但仍然不起作用,所以我编写了这两个简单的代码,但仍然不起作用 private void textBox2_KeyDown(object sender, KeyEventArgs e) { if (e.KeyCode == Keys.Enter) { //enter key is down
private void textBox2_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
//enter key is down
//btnOK_Click(this, e);
System.Windows.Forms.MessageBox.Show("My message here");
}
}
private void textBox2_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == (char)Keys.Return)
{
//enter key is down
//btnOK_Click(this, e);
System.Windows.Forms.MessageBox.Show(((char)Keys.Return).ToString());
}
}
有什么建议吗?我读了一些类似的问题,他们说要将
IsInputKey
属性设置为true,但我在任何地方都找不到它。我使用的是Visual Studio 2008在我看来,您正在寻找类似的东西
private void textBox2_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Escape)//should be replaced with enter
{
button1.PerformClick();
}
}
注意:上面的代码在向下键上,而不是按键上
假设您使用的是winforms两个选项,则此代码应该可以工作:
1) 使用密钥更新事件作为
public void txt_KeyUp(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
btnOK_Click(sender, e); // or btn.PerformClick();
return;
}
}
2) 使BtnOK成为表单的AcceptButton。(注意:这将适用于表单中的所有文本框)
使用退出键而不是返回键:
using System;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
btnOK_Click(sender, e);
MessageBox.Show("My message here");
}
else if (e.KeyCode == Keys.Escape)
{
btnOK_Click(sender, e);
MessageBox.Show(((char)Keys.Escape).ToString());
}
}
private void btnOK_Click(object sender, EventArgs e)
{
MessageBox.Show("Test");
}
}
}
您还可以在KeyDown事件中检查两个键。
你也可以使用
btnOK.PerformClick();
而不是
btnOK_Click(sender, e);
IsInputKey在。请看,我尝试了btnOK.PerformClick()
和键。退出
,但仍然是相同的键起作用!我想知道为什么KeyDown
或KeyPress
不起作用:/无论如何,谢谢
btnOK_Click(sender, e);