WinForms文本框的“KeyPress”事件丢失了?
我想在文本框中添加“KeyPress”事件(WinForm)
this.textBox1.KeyPress += new System.Windows.Forms.KeyPressEventHandler(CheckKeys);
这里是’CheckKeys’:
private void CheckKeys(object sender, System.Windows.Forms.KeyPressEventArgs e) { if (e.KeyChar == (char)13) { // Enter is pressed - do something } }
这里的想法是,一旦文本框处于焦点并按下“Enter”按钮,就会发生一些事情……
但是,我的机器找不到’KeyPress’事件。 我的代码有问题吗?
更新:
我也试过把KeyDown而不是KeyPress:
private void textBox1_KeyDown(object sender, System.Windows.Input.KeyEventArgs e) { if (e.Key == Key.Return) // Enter is pressed - do something } }
仍然没有工作……
您正在混合类库,不要在WPF项目中使用Windows窗体类。 看起来像这样:
public partial class Window1 : Window { public Window1() { InitializeComponent(); this.textBox1.KeyDown += new KeyEventHandler(textBox1_KeyDown); } private void textBox1_KeyDown(object sender, KeyEventArgs e) { if (e.Key == Key.Enter) { MessageBox.Show("Enter!"); e.Handled = true; } } }
你看过KeyPress
上的文档吗? 它特别声明KeyPress事件不是由非字符键引发的; 但是,非字符键会引发KeyDown和KeyUp事件 。 使用其中一个事件应该可行。
尝试下面的步骤它会工作,bcoz我测试过它。
- 选择文本框,右键单击它,然后单击属性。
- 单击事件,然后双击KeyPress
-
然后键入以下代码。
private void textBox2_KeyPress(object sender, KeyPressEventArgs e) { if (e.KeyChar == (char)13) { //press Enter do Something Like i have messagebox below to show "wow" MessageBox.Show("wow"); } else { } }