0

When application is run, on pressing arrow keys, Left/Right/UP/Down should appear in the label. But after opening the application, the focus is on button1 and it shifts to button2 on pressing any arrow key and it continues on each arrow key press. I need something like PreventDefault() in java. The arrow key press doesn't fire the KeyDown event only. What changes should I make to make it fire?

namespace ArrowPress
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            KeyPreview = true;
        }

        private void Form1_KeyDown(object sender, KeyEventArgs e)
        {
            if(e.KeyCode == Keys.Left)
            {
                label1.Text = "Left";
            }

            if (e.KeyCode == Keys.Right)
            {
                label1.Text = "Right";
            }

            if (e.KeyCode == Keys.Up)
            {
                label1.Text = "Up";
            }

            if (e.KeyCode == Keys.Down)
            {
                label1.Text = "Down";
            }
        }
    }
}

This is how my form looks like:

enter image description here

stuartd
  • 70,509
  • 14
  • 132
  • 163
Tejashree
  • 51
  • 8
  • 1
    Possible duplicate of [How to disable navigation on WinForm with arrows in C#?](https://stackoverflow.com/questions/1318236/how-to-disable-navigation-on-winform-with-arrows-in-c) – stuartd Mar 18 '20 at 12:16
  • Maybe `e.SuppressKeyPress = true` before first `if` statement? – Roman Mar 18 '20 at 12:20
  • KeyPreview is a VB6 compatibility property. It doesn't work for keys that VB6 used to implement navigation. Like the cursor keys. Multiple ways to fix that, like PreviewKeyDown, [ProcessCmdKey() is another](https://stackoverflow.com/a/400325/17034). – Hans Passant Mar 18 '20 at 12:26
  • @stuartd hey...I tried that solution and it worked. Thanks :) – Tejashree Mar 18 '20 at 12:29

0 Answers0