gpt4 book ai didi

c - 在 C 和 Win32 api 中轮询键盘

转载 作者:太空宇宙 更新时间:2023-11-04 02:30:32 25 4
gpt4 key购买 nike

这段代码没有做它应该做的事。

enter image description here

当我按一次光标键时,菜单跳转不止一次。

我该如何解决这个问题?

.

相关源码

#include <windows.h>
#include <conio.h>

BOOL IsKeyPressed(KEY_CODE key)
{
if (GetAsyncKeyState(key) < 0)
{
return TRUE;
}
else
{
return FALSE;
}
}

int select_menu(char**menus, int x, int y, int items_count)
{
int selection = 0;
show_menu(x, y, menus, items_count);
gotoxy(x, y);

while (1)
{
if (IsKeyPressed(vk_Down))
{
int xx = wherex();
int yy = wherey() + 1;

if ((yy - x + 1) > items_count)
{
gotoxy(x, y);
}
else
{
gotoxy(xx, yy);
}
}
if (IsKeyPressed(vk_Up))
{
int xx = wherex();
int yy = wherey() - 1;

if (yy < y)
{
gotoxy(x, y + items_count);
}
else
{
gotoxy(xx, yy);
}
}
if (IsKeyPressed(vk_Return))
{
int xx = wherex();
int yy = wherey();

selection = yy - y + 1;
}
}

return selection;
}

引用:

https://sourceforge.net/projects/conio/

最佳答案

您遇到了软件反弹。

来自 Microsoft 页面。 GetAsyncKeyState :

确定在调用该函数时某个键是按下还是按下,以及该键是否在上次调用 GetAsyncKeyState 后被按下。

函数返回提供两条信息:
1. 按键瞬时状态。
2. key 的历史状态(自上次调用以来)。
您应该了解并使用两者来做出决定。

为了防止弹跳,看一下返回值的说明:

If the function succeeds, the return value specifies whether the key was pressed since the last call to GetAsyncKeyState, and whether the key is currently up or down. If the most significant bit is set, the key is down, and if the least significant bit is set, the key was pressed after the previous call to GetAsyncKeyState. However, you should not rely on this last behavior; for more information, see the Remarks. [emhpasis mine]

例如,您可以专门为每个条件编写函数:

BOOL IsKeyPressed(KEY_CODE key)
{
if(0x80000000 & GetAsyncKeyState(key))//most significant bit is high
return TRUE; //key IS down
else return FALSE;
}

BOOL WasKeyDown(KEY_CODE key)
{
if(0x00000001 & GetAsyncKeyState(key))//least significant bit is high
return TRUE; //key WAS down
else return FALSE;
}

如果在某些时候可能需要查看历史当前状态,同时您正在监视多个按键,此示例说明了如何执行此操作。特别是,此代码定义了一组可用于终止应用程序的 key :

void KillThisApp(void)
{
if ((0x80000000 & GetAsyncKeyState(VK_CONTROL)) ||
(0x00000001 & GetAsyncKeyState(VK_CONTROL)))
{
if ((0x80000000 & GetAsyncKeyState('k')) ||
(0x00000001 & GetAsyncKeyState('k')) ||
(0x80000000 & GetAsyncKeyState('K')) ||
(0x00000001 & GetAsyncKeyState('K')) )
{
if((0x80000000 & GetAsyncKeyState(VK_SHIFT)) ||
(0x00000001 & GetAsyncKeyState(VK_SHIFT)))
{
gRunning = FALSE;
}
}
}
}

这个版本不关心键是 is down 还是 was down,但是可以很容易地编辑以要求所有键 在通过在每次调用期间仅查看高位来调用

关于c - 在 C 和 Win32 api 中轮询键盘,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43924775/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com