-1

I am developing an aplication in which i play a sound in a loop. I want the loop to stop on either mouse click or key press and restart the loop. I am using c#, .net. Problem I am facing is loop continues to execute without capturing input from mouse/keyboard until it reaches to its maximum specified value. My code is

for(soundVolume = 0; soundVolume < 10; soundVolume++)
{
sound.Play();
if(mouseClick == true)
    {
    soundVolume = 0;
    }
}
Blorgbeard
  • 101,031
  • 48
  • 228
  • 272

1 Answers1

0

You have to use your loop in another Thread than UI Thread.

I have used CheckForIllegalCrossThreadCalls=false Here just for the sake of simplicity. but if you don't use that, you will face with an error which shows you want to access to the UI Thread from another Thread. which has to be handled in a better way that is discussed here

But for now, this Sample code fulfills your need.

        bool mouseClick =false;
        private void Form1_Load(object sender, EventArgs e)
        {
            CheckForIllegalCrossThreadCalls = false;
        }

        private void Form1_MouseClick(object sender, MouseEventArgs e)
        {
            mouseClick = true;
        }

        private void button1_Click(object sender, EventArgs e)
        {
        var x=new Action(doit).BeginInvoke(null,null); //Do something in other thread that UI Thread
        }

        private void doit()
        {
            for(soundVolume = 0; soundVolume < 10; soundVolume++)
            {
              sound.Play();
             if(mouseClick == true)
              {
               soundVolume = 0;
              }
            }
        }
    }
Community
  • 1
  • 1
Mehrdad Kamelzadeh
  • 1,764
  • 2
  • 21
  • 39