Home > OS >  (Windows)Can I get the program to be changed or be stopped while it is running?
(Windows)Can I get the program to be changed or be stopped while it is running?

Time:05-20

I am now writing a win32 program in C . I want to show my running process on the window, just like time is flowing.

For example, this code

int a=0;
for(int i=0;i<10;i  )
{
  a  ;//The change in "a" can be seen on the window.
  Sleep(1*1000);
}

But I've found that if I want to show this process, like clicking a button and a changing number appears on the screen, then the program needs to be running all the time. At this point, I don't have a way to do anything else, like clicking on another button.

So I realized I needed an operation that could interrupt the current process. But I went through a lot of information and found that only the fork() function of the Linux system can meet my needs. But I'm using Windows now, so what other ways can I achieve this? Sincerely look forward to your reply.

CodePudding user response:

You want to create a timer with SetTimer. Then watch for the WM_TIMER messages and update the screen then. This is the standard way of achieving what you described.

CodePudding user response:

Create a thread and use atomic.

std::atomic_int a_t(0);

auto do_a = [](std::atomic_int* pA)
{
for (int i = 0;i < 10;i  )
{
    (*pA)  ;
    std::this_thread::sleep_for(1s);
}
};

thread t(do_a, &a_t);
t.join();
cout << a_t.load(memory_order::memory_order_relaxed);

Anytime you need get the value of a_t , just call a_t.load(memory_order::memory_order_relaxed);

Hope this helps you

  • Related