Detecting arrows keys in winforms

23,346

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.

Share:
23,346
Win Coder
Author by

Win Coder

Updated on July 09, 2022

Comments

  • Win Coder
    Win Coder almost 2 years

    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.