T
T
Tolyambaqq2015-12-04 13:31:36
visual studio
Tolyambaqq, 2015-12-04 13:31:36

Customizing label control in c# from keyboard?

Can't setup keyboard controls for label in c#
private void label1_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e)
{
switch (e.KeyCode.ToString())
{
case "Down":
label1.Top += 45;
break;
case "Up":
label1.Top -= 45;
break;
case "Left":
label1.Left -= 45;
break;
case "Right":
label1.Left += 45;
break;

Answer the question

In order to leave comments, you need to log in

2 answer(s)
E
eRKa, 2015-12-05
@kttotto

The problem is that you added event handling to label1, but it was necessary for Form1. Just checked, everything works.

private void Form1_KeyDown(object sender, KeyEventArgs e)
        {
            switch (e.KeyCode.ToString())
            {
                case "Down":
                    label1.Top += 45;
                    break;

                case "Up":
                    label1.Top -= 45;
                    break;

                case "Left":
                    label1.Left -= 45;
                    break;

                case "Right":
                    label1.Left += 45;
                    break;
            }
        }
    }

Just don’t write comme il faut like this e.KeyCode.ToString()
Option is more beautiful)
switch (e.KeyCode)
            {
                case Keys.Down:
                    label1.Top += 45;
                    break;

                case Keys.Up:
                    label1.Top -= 45;
                    break;

                case Keys.Left:
                    label1.Left -= 45;
                    break;

                case Keys.Right:
                    label1.Left += 45;
                    break;
            }

M
Melz, 2015-12-05
@melz

The problem is different. Try using TextBox instead of Label and your code will work.
The problem lies precisely in the selected control. PreviewKeyDown is fired before the KeyDown event when a key is pressed while the control has focus.
Label is not an input control and therefore does not receive focus (such gray dots / lines around) during operation.
This is your case - the arrows will be ignored.
If you add a bunch of controls to a form and press TAB, the label won't get the focus.
Therefore, or do it globally, as mentioned above, on the form.
Or take a TextBox, set it to ReadOnly and make it look like a Label in the properties. Well, there is a system background, remove the border, and so on.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question