0

So I am trying to move a label with arrow keys up and down while it is moving right. I have got a timer moving it right and then teleporting it back to the start when it hit the edge. I have got this code to do it but when I run it it moves right but when I press the arrow keys it isn't working:

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private void btn_start_Click(object sender, EventArgs e)
    {
        tmr_move.Start();
        lbl_move.Text = "Hello World! I am moving!";
    }

    private void tmr_move_Tick(object sender, KeyEventArgs e)
    {
        lbl_move.Location = new Point(lbl_move.Location.X + 2, lbl_move.Location.Y);

        if (lbl_move.Location.X > this.Width)
        {
            lbl_move.Location = new Point(0 - lbl_move.Width, lbl_move.Location.Y);
        }
        switch (e.KeyCode)
        {
            case Keys.Up:
                lbl_move.Location = new Point(lbl_move.Location.X, lbl_move.Location.Y - 1);
                break;
            case Keys.Down:
                lbl_move.Location = new Point(lbl_move.Location.X, lbl_move.Location.Y + 1);
                break;
        }
    }
}
  • `tmr_move_Tick` name is confusing. assuem it is key event handler. have you set `Form.KeyPreview = true`? and you'd better disable time to isolate testing keyboard events. – Lei Yang Mar 24 '22 at 03:51
  • @LeiYang `tmr_move_Tick` is the name for the tick of the timer. I don't believe I have set Form.KeyPreview to True. – sirOrange17 Mar 24 '22 at 06:11
  • timer event handler shouldn't have `KeyEventArgs`. i'm wondering your code compiles? please also paste code of event handler **reigstration**. – Lei Yang Mar 24 '22 at 06:12

0 Answers0