【问题标题】:Pause loop until certain key is pressed暂停循环,直到按下某个键
【发布时间】:2014-08-07 16:07:19
【问题描述】:

我在我的主函数中使用了一个如下所示的循环:

while (1)
{
cout << "Hello world" << endl;
}

我将如何暂停此循环并在按下键时恢复? 例如:当我按住 [TAB] 时,循环运行。当我放手时,循环再次暂停。

【问题讨论】:

  • 重复“等待用户输入”
  • 不再需要 5 个用户作为副本关闭吗?
  • @CashCow 我不同意这个重复,用户想循环 while TAB 键被按下,这不能在标准 C 中完成。
  • @CashCow 如果您使用例如getchar 那么输入必须以换行符结束,程序才能读取输入。
  • 我推荐_getch,而不是ReadConsoleInput

标签: c++ winapi


【解决方案1】:

你可以使用函数GetAsyncKeyState()

这是一个符合您描述的改编:
EDITED 允许在 SHIFT 时退出循环strong> 按键被击中。

#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;   
}

【讨论】:

  • 你好。感谢您尝试提供帮助,尽管这并不能真正解决我的问题。在这种情况下,仍然有一个无限循环在运行,这很糟糕。但也许你无法避免这个循环?
  • @user3052603 查看我的编辑(大约两分钟后)。将while(1)修改为while(running)
【解决方案2】:

我不知道你是否打算使用线程...但是我想出了一个解决方案,将循环放在线程内,然后在主线程上检查 TAB 键状态。如果按键被按下,主线程唤醒循环线程,如果没有按下,主线程挂起循环线程。看看吧:

#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);
    }
}

我的 main 使用循环来一直检查按键...但是您可以在程序的特定点上执行此操作,避免无限循环。

【讨论】:

    猜你喜欢
    • 2021-05-26
    • 2017-07-03
    • 2022-01-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多