I don't know if you are planning to use threads... But I came up with a solution that places the loop inside a thread and then, on the main thread, checks for the TAB key state. If the key is pressed the main thread awakes the loop thread, if it is not pressed, the main thread hangs the loop thread. Check it out:
#include<windows.h>
#include<iostream>
using namespace std;
bool running = false;
DWORD WINAPI thread(LPVOID arg)
{
while (1)
{
cout << "Hello world" << endl;
}
}
void controlThread(void)
{
short keystate = GetAsyncKeyState(VK_TAB);
if(!running && keystate < 0)
{
ResumeThread(h_thread);
running = true;
}
else if(running && keystate >= 0)
{
SuspendThread(h_thread);
running = false;
}
}
int main(void)
{
HANDLE h_thread;
h_thread = CreateThread(NULL,0,thread,NULL,0,NULL);
SuspendThread(h_thread);
while(1)
{
controlThread();
//To not consume too many processing resources.
Sleep(200);
}
}
My main uses a loop to keep checking for the keypress forever... But you can do that on specific points of your program, avoiding that infinite loop.