Detecting arrows keys in winforms [duplicate]

2020-02-28 23:22发布

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

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.

标签: c# .net keypress
1条回答
贪生不怕死
2楼-- · 2020-02-29 00:04

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

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.

查看更多
登录 后发表回答