Hi everyone.

I am creating a small windows form application using Visual C++; and I would need to delay a loop by a second. Sleep() doesn't work.(Not sure why) Is there a way I can use the timer? Any suggestions on how can I do that?

Thanks in advance. :)

How do you know Sleep() doesn't work?? Recall the parameter is milliseconds -- there are 1000 milliseconds in one second.

How do you know Sleep() doesn't work?? Recall the parameter is milliseconds -- there are 1000 milliseconds in one second.

Yeah, I know. It is still not working. Well, it does work when I do a console application, but not when I do it in the Forms app.


The following does not work:

private: System::Void button1_Click(System::Object^  sender, System::EventArgs^  e) {

				 for (int k = 0; k < 10; k++)
				    {
				   	 Sleep(1000);
					  label1->Text = Convert::ToString (k);
				    }
				 
			 }

What do you mean by "it doesn't work"?

What do you mean by "it doesn't work"?

Well, it should change the Text of label1 from 1 to 9, with a 1 second interval. However it does not, it shows me, a 9 right away, when I click the button.

It looks like you're using managed C++, so try using:

using namespace System::Threading;
Thread::Sleep(1000);

I'm surprised that you find plain old Sleep() available, so perhaps you're picking up an odd version of Sleep from somewhere in your codebase.

MrSpigot, this is not working either :(

using namespace System::Threading;
Thread::Sleep(1000);

why don't you make your own function using <ctime>? Just let it loop for a second every time.

why don't you make your own function using <ctime>? Just let it loop for a second every time.

Yeah, Tigran, that was a good idea.
I did something like

Time b,c; // class Time,  Constructs a Time object that is set to 
  //    the time at which the constructor executes.

// the rest is pretty clear.

int t1 = b.get_seconds(); // seconds at that time. when b was created;
int t2;
 while (true)
 {
         Time c;  t2 = c.get_seconds(); if (t2==t1+5) break; // creates //new c each time, (+5) indicates 5 seconds delay. 
 };

But anyways, I would like to know how Timer works in Visual c++.
Thanks.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.