C# 检测winforms中的箭头键

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13163447/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 01:49:58  来源:igfitidea点击:

Detecting arrows keys in winforms

c#.netkeypress

提问by Win Coder

Possible Duplicate:
Up, Down, Left and Right arrow keys do not trigger KeyDown event

可能的重复:
向上、向下、向左和向右箭头键不会触发 KeyDown 事件

First see the code.

先看代码。

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading;
namespace winform_project
{
 public partial class Form1 : Form
 {

    public Form1()
    {
        InitializeComponent();

    }

    private void Form1_KeyPress(object sender, KeyPressEventArgs e)
    {
        MessageBox.Show("Hello");
    }
 }
}

I am able to detect alpha-numeric keys. However i am not able to detect arrow keys.

我能够检测字母数字键。但是我无法检测到箭头键。

Any help would be appreciated in this regard.

在这方面的任何帮助将不胜感激。

采纳答案by Win Coder

Ok so after some research i found out the simplest way to handle arrow key events is to override the ProcessCmdKey method.

好的,经过一些研究,我发现处理箭头键事件的最简单方法是覆盖 ProcessCmdKey 方法。

protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
{
     if(keyData == Keys.Left)
     {
       MessageBox.Show("You pressed Left arrow key");
       return true;
     }
     return base.ProcessCmdKey(ref msg, keyData);
}

Hope this helps.

希望这可以帮助。