There was a problem, the event of pressing a key in a form does not work.

private void Form1_KeyDown_1(object sender, KeyEventArgs e) { if (e.KeyCode == Keys.Up && sn.course != Snake.Course.DOWN) { sn.course = Snake.Course.UP; } if (e.KeyCode == Keys.Down && sn.course != Snake.Course.UP) { sn.course = Snake.Course.DOWN; } if (e.KeyCode == Keys.Left && sn.course != Snake.Course.RIGHT) { sn.course = Snake.Course.LEFT; } if (e.KeyCode == Keys.Right && sn.course != Snake.Course.LEFT) { sn.course = Snake.Course.RIGHT; } } 

The Snake class is written in another file. In the Form1 class, a public Snake sn; field was created public Snake sn; Here are the fields of the Snake class.

 public class Snake { public List<Rectangle> lSnake = new List<Rectangle>(); private int sLong = 3; public int addX, addY; public enum Course { UP, DOWN, LEFT, RIGHT }; public Course course; } 
  • four
    Yes, I have already notified Microsoft. They will fix C # for the next release. Previously, for some reason, no one noticed that pressing the keys in the form does not work. - VladD
  • Just a joke is that if I run another code, where everything is in 1 file, everything works fine. - Dementir
  • Yes? Well, thank God, then everything is canceled. - VladD
  • Then what could be the problem? - Dementir
  • But the option did not occur to you that there was no problem with the event of pressing the button, but are they in your code? Well, theoretically, I mean nothing? - VladD

1 answer 1

Set the Form1 property value in the Properties window of the Form1 property to KeyPreview = true , or

 public Form1() { InitializeComponent(); this.KeyPreview = true; } 
  • Thank you so much! Everything works now! - Dementir
  • If it is not difficult to mark the answer as correct. - Lada