nyanagharo
nyanagharo

Reputation: 38

How do I stop an Application DoEvents loop in C++?

This is a Visual Studio Express C++ Windows Forms application.

I want to play a WAV file strFileName.WAV in a WAV play wavPlayer every 10 seconds from the time I press the "Start" button until such time as I press the "Stop" button.

When each 10 second interval is up, TimerEventProcessor plays the WAV file.

The problem is that I have to press "Stop" twice to get it to work. The first press of "Stop" seems to be ignored.

Why is btnStop_Click not executing the first time I press "Stop"?

private: System::Void bntStart_Click(System::Object^  sender, System::EventArgs^  e) {
  if (String::IsNullOrEmpty(strFileName)) {
    lblRunning->Text = L"Cannot Start Until File Is Loaded";
  }
  else {
    lblRunning->Text = L"Running";   
    myTimer->Interval = iIntervalSeconds * 1000;
    myTimer->Tick += gcnew EventHandler( TimerEventProcessor );
    myTimer->Enabled = true;
    while (lblRunning->Text == L"Running") {
      Application::DoEvents();
    }
  }
}

private: System::Void btnStop_Click(System::Object^  sender, System::EventArgs^  e) {
  lblRunning->Text = L"Stopped";
  myTimer->Enabled = false;
  wavPlayer->Stop();
}

Upvotes: 1

Views: 774

Answers (1)

shf301
shf301

Reputation: 31394

Get rid of the

while (lblRunning->Text == L"Running") {
  Application::DoEvents();
}

loop. When you return from bntStart_Click the form will return to dispatching messages and the timer will tick as expected. There is no need for you to create a manual Application::DoEvents() loop, which is probably the cause of your problem.

By calling Application::DoEvents(); in a loop you are creating a pooling loop for window messages. Without any sleep call this loop cause 100% CPU usage. By letting your bntStart_Click return the WinForms runtime will sleep your process until a message is ready - resulting in very low CPU usage.

This high CPU usage is probably making your application unresponsive which is why it seems that clicks are not being processed.

Upvotes: 3

Related Questions