且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在C#中以用户控件的形式获取所有KeyPress事件?

更新时间:2022-11-07 19:22:19

  • 将父窗体的(包含用户控件)KeyPreview属性设置为true
  • 将新的KeyPress事件添加到您的父表单中
    • Set your parent form's (contains the usercontrol) KeyPreview property to true
    • Add a new KeyPress event to your parent form
    • 设置父窗体的按键事件以将事件转发到您的用户控件:

      Set the parent form keypress event to forward the event to your usercontrol:

private void parentForm_KeyPress(object sender, KeyPressEventArgs e)
        {
            // Forward the sender and arguments to your usercontrol's method
            this.yourUserControl.yourUserControl_KeyPress(sender, e);
        }

yourUserControl1_KeyPress方法替换为您自己的方法,您想在用户每次按下按钮(按下按钮然后释放按钮)时运行该方法.

Replace the yourUserControl1_KeyPress method with your own method, which you want to run each time the user presses a button (the button is pressed down and then released).

您还可以为用户控件创建一个新的KeyPress处理程序,然后在该示例中转发sender和KeyPressEventArgs对象.

You can also create a new KeyPress handler to your usercontrol, and forward the sender and KeyPressEventArgs objects there, as in this example.