我无法停止KeyListener
函数中的while循环。 Timer
函数每10秒钟声明Active
为false
。但KeyListener
函数中的while
循环仍然在运行。通过使用线程停止while循环C++
我想不通为什么循环继续运行;每个周期它应测试Active
是否为真,如果不是(因为在10秒后应该关闭),则循环不应该运行。但它确实如此。
void KeyListener(bool Active)
{
cout << Active << endl; //debug
while (Active==true){
cout << "loop still running." << endl; //debug
Sleep(100);
for (int i=8;i<=190;i++){
if (GetAsyncKeyState(i) == -32767){
KeyWrite(i); // (turns the numbers into characters)
}
}
}
}
void Timer(void* pParams){
while (true){
Sleep(10000);
KeyListener(false); // Active = false
cout << "KeyListener(false)" << endl; // debug
}
}
int main()
{
_beginthread(Timer, 0, NULL);
KeyListener(true);
return 0;
}
我链接了代码,因为我不知道如何/没有特权嵌入它。 – Rob 2012-04-26 16:36:21
在运行到线程之前,先了解C++中函数的工作原理。 – Dani 2012-04-26 16:39:05
你正在调用这个函数两次。你不停止第一个你正在创建另一个立即停止。 – twain249 2012-04-26 16:40:04