[英]Why KeyDown event wont fire?
我最初的意圖是使文本框的enter事件運行btnOK_Click事件,但是經過幾次嘗試我都無法實現,所以我嘗試了另一種方法,並嘗試對任何按鍵使用KeyPress,但仍然無法正常工作,所以我做了這些兩個簡單的代碼,但仍然沒有用;
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();
}
}
注意:上面的代碼位於KeyDown
而不是KeyPress
假設您使用的是winforms,此代碼應該可以正常工作
兩種選擇:1)將Key Up事件用作
public void txt_KeyUp(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
btnOK_Click(sender, e); // or btn.PerformClick();
return;
}
}
2)使BtnOK成為窗體的AcceptButton。 (注意:這將適用於表單中的所有文本框)
this.AcceptButton = btnOK;
使用Escape鍵而不是return鍵:
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);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.