c# – WinForms文本框的“KeyPress”事件丢失了?

前端之家收集整理的这篇文章主要介绍了c# – WinForms文本框的“KeyPress”事件丢失了?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我试图在文本框中添加“KeyPress”事件(WinForm)
  1. this.textBox1.KeyPress += new System.Windows.Forms.KeyPressEventHandler(CheckKeys);

而这里是’CheckKeys’:

  1. private void CheckKeys(object sender,System.Windows.Forms.KeyPressEventArgs e)
  2. {
  3. if (e.KeyChar == (char)13)
  4. {
  5. // Enter is pressed - do something
  6.  
  7. }
  8. }

这里的想法是,一旦文本框处于焦点并按下“Enter”按钮,就会发生一些事情……

但是,我的机器找不到’KeyPress’事件.
我的代码有问题吗?

更新:

我也试过把KeyDown而不是KeyPress:

  1. private void textBox1_KeyDown(object sender,System.Windows.Input.KeyEventArgs e)
  2. {
  3.  
  4. if (e.Key == Key.Return)
  5.  
  6. // Enter is pressed - do something
  7. }
  8. }

仍然没有工作……

解决方法

您正在混合类库,不要在WPF项目中使用Windows窗体类.看起来像这样:
  1. public partial class Window1 : Window {
  2. public Window1() {
  3. InitializeComponent();
  4. this.textBox1.KeyDown += new KeyEventHandler(textBox1_KeyDown);
  5. }
  6.  
  7. private void textBox1_KeyDown(object sender,KeyEventArgs e) {
  8. if (e.Key == Key.Enter) {
  9. MessageBox.Show("Enter!");
  10. e.Handled = true;
  11. }
  12. }
  13. }

猜你在找的C#相关文章