简体   繁体   English

如何在C#.NET表单上捕获按键

[英]How to catch a key press on a C# .NET form

I have a parent form that contains a lot of controls. 我有一个包含很多控件的父表单。 What I am trying to do is filter all of the key presses for that form. 我想要做的是过滤该表格的所有按键。 The trouble is that if the focus is on one of the controls on the form then the parent form is not getting the key press event, so how do I capture the key down event? 麻烦的是,如果焦点在表单上的一个控件上,那么父表单没有获得按键事件,那么如何捕获按键事件?

在表单上将KeyPreview设置为true,您将捕获它们: MSDN

This will only work on form, but not if any other component is in focus 这仅适用于表单,但如果任何其他组件处于焦点位置则不会

public partial class ChildForm : Form
{

    public ChildForm()
    {       
       KeyPress += KeyPressHandler;
    }

    public KeyPressHandler(object sender, KeyPressEventArgs e)
    {
       if (_parent != null)
       {
           _parent.NotifyKeyPress(e);
       } 
    }
}

This will work even when other components are in focus 即使其他组件处于焦点,这也会起作用

protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
{
    if (keyData == Keys.F1)
    {
        MessageBox.Show("You pressed the F1 key");
        return true;    // indicate that you handled this keystroke
    }

    // Call the base class
    return base.ProcessCmdKey(ref msg, keyData);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM