1

I saw on the internet the solution was setting the KeyPreview to true. I have tried it, and it still didn't work. Why when I press one of the arrows (down, up, left, or right) the label still doesn't show off?

To make this clear: a regular letter does work and makes the label show off. The thing is that the arrows (down, up, left or right) don't work. I think I know why - the "focus" is on the button and not on the form. I searched for this on the internet, and I found that I need to make the KeyPreview set as true. I did it, and still, it doesn't show the label when I press the arrows, only when I press letters. If I remove the button, the arrows do work.

Here is my code:

public partial class Form1: Form
    {
        public Form1()
        {
            InitializeComponent();
            label1.Visible = false;
            this.KeyPreview = true;
            this.KeyDown += Form1_KeyDown;
        }

        private void Form1_KeyDown(object sender, KeyEventArgs e)
        {
            label1.Visible = true;
        }

        private void button1_Click(object sender, EventArgs e)
        {

        }
    }
avocadoLambda
  • 1,332
  • 7
  • 16
  • 33
  • 1
    Try on of the solutions from this: https://stackoverflow.com/questions/1646998/up-down-left-and-right-arrow-keys-do-not-trigger-keydown-event – Kevin Jun 25 '20 at 14:04
  • 1
    [How to change focus on buttons up, down, left and right relative to the button that is selected?](https://stackoverflow.com/a/59666527/7444103) – Jimi Jun 25 '20 at 14:10

1 Answers1

2

Overriding ProcessCmdKey() works for me, even with KeyPreview turned OFF:

public Form1()
{
    InitializeComponent();
    label1.Visible = false;
}

protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
{
    switch (keyData)
    {
        case Keys.Left:
        case Keys.Right:
        case Keys.Up:
        case Keys.Down:
            label1.Visible = true;
            break;
    }
    return base.ProcessCmdKey(ref msg, keyData);
}
Idle_Mind
  • 38,363
  • 3
  • 29
  • 40