我试图在文本框中添加“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 } }
仍然没有工作……
解决方法@H_502_23@
您正在混合类库,不要在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;
}
}
}
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; } } }