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.
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:
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With