Control.PreviewKeyDown 事件

定义

在焦点位于此控件上的情况下,当有按键动作时发生(在 KeyDown 事件之前发生)。

C#
public event System.Windows.Forms.PreviewKeyDownEventHandler PreviewKeyDown;
C#
public event System.Windows.Forms.PreviewKeyDownEventHandler? PreviewKeyDown;

事件类型

示例

下面的代码示例演示包含 ButtonContextMenuStripButton当 具有焦点并且按向上键或向下键时,ContextMenuStrip将显示 。 事件处理程序 PreviewKeyDown 检测何时按下向上键或向下键,并将 属性设置为 IsInputKeytrue。 这会引发 KeyDown 事件,以便可以显示 ContextMenuStrip。 不应将任何逻辑放入事件处理程序中 PreviewKeyDown ,而不应设置 IsInputKey 属性。 相反,应将逻辑放入 KeyDown 事件处理程序中。

C#
public Form1()
{
    InitializeComponent();

    // Form that has a button on it
    button1.PreviewKeyDown +=new PreviewKeyDownEventHandler(button1_PreviewKeyDown);
    button1.KeyDown += new KeyEventHandler(button1_KeyDown);
    button1.ContextMenuStrip = new ContextMenuStrip();
    // Add items to ContextMenuStrip
    button1.ContextMenuStrip.Items.Add("One");
    button1.ContextMenuStrip.Items.Add("Two");
    button1.ContextMenuStrip.Items.Add("Three");
}

// By default, KeyDown does not fire for the ARROW keys
void button1_KeyDown(object sender, KeyEventArgs e)
{
    switch (e.KeyCode)
    {
        case Keys.Down:
        case Keys.Up:
            if (button1.ContextMenuStrip != null)
            {
                button1.ContextMenuStrip.Show(button1,
                    new Point(0, button1.Height), ToolStripDropDownDirection.BelowRight);
            }
            break;
    }
}

// PreviewKeyDown is where you preview the key.
// Do not put any logic here, instead use the
// KeyDown event after setting IsInputKey to true.
private void button1_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e)
{
    switch (e.KeyCode)
    {
        case Keys.Down:
        case Keys.Up:
            e.IsInputKey = true;
            break;
    }
}

注解

某些按键(如 TAB、RETURN、ESC 和箭头键)通常被某些控件忽略,因为它们不被视为输入按键。 例如,默认情况下, Button 控件会忽略箭头键。 按箭头键通常会导致焦点移动到上一个或下一个控件。 箭头键被视为导航键,按这些键通常不会引发 KeyDown 的事件 Button。 但是,按 的 Button 箭头键会引发 PreviewKeyDown 事件。 通过处理 PreviewKeyDown 的事件 Button 并将 属性设置为 IsInputKeytrue,可以在按下箭头键时引发 KeyDown 事件。 但是,如果处理箭头键,焦点将不再移动到上一个或下一个控件。

有关处理事件的详细信息,请参阅 处理和引发事件

适用于

产品 版本
.NET Framework 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
Windows Desktop 3.0, 3.1, 5, 6, 7, 8, 9, 10