I'm not new to C++, but i figured this would be the proper forum to ask a question like this in. I have not used functions declared as void until now because i had no need for them. But recently, i wrote a timer app and when the timer is done, it beeps in incriments while showing a "flashing" 'TIMER DONE!' message for the user. The user can then press any of the 4 buttons to turn the alert off: Space, Backspace, escape, or enter. Because a while loop is required for a continual alert, i used GetAsyncKeyState() to recieve the input. The problem is that GetAsyncKeyState() "gets" the key regardless of whether the program is the domonant one at the time. I could be browsing the web and turn off the alarm even though the program is minimized. Also, if you pressed the Enter key or any other deactivation key before starting the alarm, it would create the effect of the alarm not sounding. It would think you pressed the button and turn off immediately, when the alarm sounds, creating the effect of no alarm sounding at all. So, naturally, i decided to experiment with a different approach: What if we called a void function to execute the alarm, and then have a loop to get input with _getch(). Since _getch() requires a pause it is necessary that the function being called does not return a value.
Here is the sample code (t_done() is called first, becaude we dont want to call it more than once):
1 2 3 4 5 6 7 8 9 10 11 12 13 14
|
void t_done();
while(x == 0)
{
clrg();
ch = _getch();
if((ch == 0x0d) || (ch == 0x08) || (ch == 0x1b) || (ch == 0x20))
{
cls();
clrg();
break;
}
}
return 0;
}
|
t_done() code:
1 2 3 4 5 6 7 8 9 10 11 12
|
void t_done()
{
int x = 0;
while(x == 0)
{
cls();
cout<< "TIMER DONE!";
Beep(1500, 500);
cls();
Sleep(500);
}
}
|
clrg() code:
1 2 3 4 5 6
|
int clrg()
{
Sleep(100);
while(_kbhit()) _getch();
return 0;
}
|
cls() code:
1 2 3 4 5
|
int cls()
{
system("CLS");
return 0;
}
|
i have obvserved different behavior each time i execute it. The first time it works as expected. The second time it doesnt sound the alarm and blanks the screen while waiting for input (as if skipping the t_done() all together). After that the same thing... My reason for this approach is simple: Because void functions do not return a value, the program will not wait for the function to finish before executing the remaining instructions. When I call t_done
t_done();
though, it acts like any other function. The only thing that has yeilded promising results was calling it
void t_done();
. Unfortunatly, it yeilds different results each time and still ignores the clrg() when accepting input. During tests i would press [enter] during a 5 second countdown and it would act as though i had pressed it while the alarm was sounding, which indicates it did not clear the _getch() stream at all. I would appreciate any help I can get! Thank you ahead of time.