Reputation: 135
I'm using a loop within my main function that looks like this:
while (1)
{
cout << "Hello world" << endl;
}
How would I go about pausing this loop and resume while a key is pressed? For example: When I hold [TAB] down, the loop runs. And when I let go, the loop pauses again.
Upvotes: 1
Views: 1264
Reputation: 1007
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.
Upvotes: 0
Reputation: 23208
You can use the function GetAsyncKeyState()
Here is an adaptation that does what you describe:
EDITED to allow exit of loop when SHIFT key is hit.
#include <stdio.h> //Use these includes: (may be different on your environment)
#include <windows.h>
BOOL isKeyDown(int key) ;
int main(void)
{
int running = 1;
while(running)
{
while(!isKeyDown(VK_TAB)); //VK_TAB & others defined in WinUser.h
printf("Hello World");
Delay(1.0);
if(isKeyDown(VK_SHIFT)) running = 0;//<SHIFT> exits loop
}
return 0;
}
BOOL isKeyDown(int key)
{
int i;
short res;
res = GetAsyncKeyState(key);
if((0x80000000 &res != 0) || (0x00000001 & res != 0)) return TRUE;
return FALSE;
}
Upvotes: 1