Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detecting arrows keys in winforms [duplicate]

Tags:

c#

.net

keypress

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.

like image 823
Win Coder Avatar asked Oct 31 '12 17:10

Win Coder


People also ask

How do I detect arrow keys in Windows Forms?

Detecting arrow keys Detecting arrow keys in winforms C# and vb.net Most Windows Forms applications process keyboard input exclusively by handling the keyboard events. You can detect most physical key presses by handling the KeyDown or KeyUp events. Key events occur in the following order:

How do I detect keystrokes in a form?

Here's an example: The appropriate event to use is either keyup, or keydown. You can detect the keys either at the form level, or at the image-control level. If you wish to process at the form-level (before the image control gets the event), then set the form's KeyPreview property to true.

How to detect arrow key presses by listening to the event?

Also, we can use addEventListener method to add the key down listener by writing: We can detect arrow key presses by listening to the keydown event. And in the event listener, we can either check the key or keydown properties of the event object to see which key is pressed.

What are the events for arrow key movement in forms?

Arrow Key movement on Forms c# and vb.net In most cases, the standard KeyUp, KeyDown, and KeyPress events are enough to catch and handle keystrokes. However, not all controls raise these events for all keystrokes under all conditions.


1 Answers

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.

like image 90
Win Coder Avatar answered Sep 28 '22 03:09

Win Coder