加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-15 04:18:03 所属栏目:百科 来源:网络整理
导读:我试图在文本框中添加“KeyPress”事件(WinForm) this.textBox1.KeyPress += new System.Windows.Forms.KeyPressEventHandler(CheckKeys); 而这里是’CheckKeys’: private void CheckKeys(object sender,System.Windows.Forms.KeyPressEventArgs e){ if (e
我试图在文本框中添加“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;
      }
    }
  }

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读