在winforms中检测箭头键

时间:2012-10-31 17:23:42

标签: c# .net keypress

  

可能重复:
  Up, Down, Left and Right arrow keys do not trigger KeyDown event

首先看代码。

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");
    }
 }
}

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

在这方面,我们将不胜感激。

1 个答案:

答案 0 :(得分:27)

好的,经过一些研究后我发现处理箭头键事件的最简单方法是覆盖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);
}

希望这有帮助。