It is necessary that some method be carried out with the "A" button pressed (not pressed, namely, clamped). And when I let her go, another method was called.

There is such a code. But for some reason the melody is played for only 1 second, and then it stops.

private void Window_KeyDown(object sender, KeyEventArgs e) { if (e.Key == Key.A) { PlaySound(); this.MyBotton.Background = Brushes.Black; } } private void PlaySound() { wpalyer.URL = @"D:123.mp3"; wpalyer.controls.play(); } private void Window_KeyUp(object sender, KeyEventArgs e) { if (e.Key == Key.A) { wpalyer.controls.stop(); this.MyBotton.Background = Brushes.White; } } 
  • wpalyer What is this type? - Anton Komyshan
  • And what is the real length of the melody? - VladD
  • And try also to display debugging information ( Debug.WriteLine("что-то") ) inside Window_KeyDown and Window_KeyUp . Может быть, . Может быть, KeyDown` is called more often than you think. - VladD
  • Or check IsRepeat . - VladD
  • @VladD, I understand what the problem is. When I hold A, the Window_KeyDown event starts to loop. Added to Window_KeyDown Debug.WriteLine ("something") and see how these "something" float in the Output window. How to remove this cycle? I thought I could put a pause, but consider this a crutch ... - batya

2 answers 2

I would recommend this way:

 private void Window_KeyDown(object sender, KeyEventArgs e) { if (e.Key == Key.A && !e.IsRepeat) // проверка на повторение { PlaySound(); this.MyBotton.Background = Brushes.Black; } } 

    Added repeat variable for verification. Since earlier the event with the clamped "A" began to loop.

     WindowsMediaPlayer wpalyer = new WindowsMediaPlayer(); bool repeat = true; private void Window_KeyDown(object sender, KeyEventArgs e) { if (e.Key == Key.A && repeat== true) { PlaySound(); this.MyBotton.Background = Brushes.Black; Debug.WriteLine("что-то"); repeat = false; } } private void PlaySound() { wpalyer.URL = @"D:\123.mp3"; wpalyer.controls.play(); } private void Window_KeyUp(object sender, KeyEventArgs e) { if (e.Key == Key.A) { wpalyer.controls.stop(); this.MyBotton.Background = Brushes.White; Debug.WriteLine("что-то из KeyUp"); repeat = true; } }