Click here to Skip to main content
15,557,873 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Im total beginner and I know I can't get proper answer from most forums. I hope this forum is friendly for noobies, because I swear I have been looking tutorials to solve this problem, but without luck.

I have created a gui form with Visual Studio 2022 on Windows with C++.

I have:
- MyForm.h
(start button)
(stop button)
-test.cpp
(function that runs a loop)

I can launch the function with the start button, but I can't stop it. I havent found out, which is the correct way to do this. Currently I'm trying to send state message for while loop (0 for start, 1 for stop).

What I have tried:

Here is my code:

MyForm.h
C++
private: System::Void startButton_Click(System::Object^ sender, System::EventArgs^ e) {
	test_function(0);
}

private: System::Void stopButton_Click(System::Object^ sender, System::EventArgs^ e) {
	test_function(1);
}


test.cpp
C++
int test_function(int stop) {
  while(stop == 0) {
     //run my code
  }
}
Posted
Updated 29-Dec-21 0:03am

1 solution

C++
int test_function(int stop) {
  while(stop == 0) {
     //run my code
  }
}

This code will continue to run until the end of time as there is nothing in the code to cause it to stop. And that means that even pressing the stop button will have no effect because your program is stuck in this infinite loop. You need to use an external flag so that the loop can check if the stop button has been pressed. Something like:
C++
private bool stop = false;
private: System::Void startButton_Click(System::Object^ sender, System::EventArgs^ e) {
    stop = false;
	test_function();
}

private: System::Void stopButton_Click(System::Object^ sender, System::EventArgs^ e) {
    stop = true;
}
void test_function() {
  while(stop == false) {
    //run my code
    }
  }
}

Although in reality this may still not work as the loop will tend to block the GUI, so use with caution.
 
Share this answer
 
v2
Comments
0x01AA 29-Dec-21 9:52am    
a.) Why, why, why: Comparing a bool with a bool to evaluate the resulting bool?
b.) Why check stop inside again to break, while it is checked allready in the while condition?
Richard MacCutchan 29-Dec-21 10:18am    
a) Why not. This code is for someone who knows very little so using the common shortcuts will just serve to confuse.
b) Because I copied OP's code and forgot.

Happy now?
0x01AA 29-Dec-21 10:24am    
Half happy, but nevertheless a 5 ;)

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900