7

我正在尝试在文本框(WinForm)中添加“KeyPress”事件

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
    }
}

虽然还是不行...

4

3 回答 3

11

您正在混合类库,不要在 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;
      }
    }
  }
于 2010-04-03T14:49:01.953 回答
5

你看过文档KeyPress?它特别指出KeyPress 事件不是由非字符键引发的;但是,非字符键确实会引发 KeyDown 和 KeyUp 事件。改为使用其中一个事件应该可以工作。

于 2010-04-03T13:19:20.333 回答
-4

尝试以下步骤它会起作用,因为我已经测试过了。

  1. 选择文本框,右键单击它,然后单击属性。
  2. 单击事件,然后双击KeyPress
  3. 然后键入以下代码。

    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
        {
        }
    }
    
于 2011-08-29T05:44:11.990 回答