Measurement Studio for VC++

cancel
Showing results for 
Search instead for 
Did you mean: 

Using Stop Button in While Loop

Here is a scenario,

Dialog contains: Start Button, Stop Button, and Static Text box

User presses start.
Program runs a while loop
nCount is incremented by 1
nCount is displayed on the Static Text box
function UpdateData(FALSE) is called

This while loop will continue until nCount = 1000;


There is a Stop Button that is considered as a Panic Stop button. Its function is to stop the while loop when the user presses it by breaking out of the while loop. My question is: How can you check if the Stop Button is pressed or not during the while loop? Somehow during the while loop, the loop needs to continuous check if the Stop Button is pressed. If the Stop Button is pressed, then the break statement is used to get out of the wh
ile loop.
0 Kudos
Message 1 of 2
(3,018 Views)
The key to getting this to work is that at some point in your loop you need to allow Windows messages to be processed so that the event handler for your stop button will get a chance to be executed. In Visual Basic you can easily do this via DoEvents and in LabWindows/CVI you have ProcessSystemEvents, but you're on your own with MFC. Here are a couple of articles you can read for more info:



Here's one way that you could do this in your application.



  1. Add a member variable for your start button called m_start, a member variable for your stop button called m_stop, and a member variable for your text box called m_output. Also add a member variable whose type is bool called m_running and initialize it to false when the dialog is created.


  2. Add a member method to your class called DoEvents and use the following code (or code from one of the articles above) in the body of the method:


    MSG msg;
    while (::PeekMessage(&msg, NULL, 0, 0, PM_NOREMOVE))
    {
    if (!::AfxGetThread()->PumpMessage())
    return;
    }




  3. Add an event handler for the start button and use the following code in the body of the method:


    m_running = true;
    for (int i = 0; i < 1000; ++i)
    {
    // If m_running is set to false via the stop button, break out of the loop.
    if (!m_running)
    break;

    // Display the current iteration in the text box.
    CNiString output;
    output << i;
    m_output.SetWindowText(output);

    // Add a delay between each iteration of the loop.
    ::Sleep(200);

    // Give Windows a chance to process messages (and handle stop button event).
    DoEvents();
    }




  4. Add an event handler for the stop button and use the following code in the body of the method:


    m_running = false;





- Elton
Message 2 of 2
(3,018 Views)